import calendar
import math
import re
import time
from datetime import datetime, timedelta, date
from urllib.request import urlopen

import requests, shutil, xlrd
import urllib.parse
from bs4 import BeautifulSoup
from django import http
from django.core.paginator import Paginator, PageNotAnInteger
from django.db import connection, transaction
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from pypinyin import pinyin
from operator import itemgetter

from administrative.search_data import SearchData
from administrative.utils import send_mssage
from announcements.models import Notice, NoticePeople
from back_management.models import topic_meeting, VoteLeader, QuestionnaireRecord, topic_sing
from finance.models import LeaveRequest, LeaveRequestAuditRecord, LeaveRequestTypeDays, \
    QuickAuthorizationApplicationCategory, QuickAuthorization, BusinessContract, ObjectAudit, TravelApply, \
    OutgoingCadresData, ConfidentialDataExport, Dimission
from medical_ethics.models import EvaluationOfMedicalEthics, EvaluationOpinion
from forum.views import str_to_timestamp
from logistics.models import *
from payment_management.models import SupportSubsidies
from personal_center.process_check import *
from django.http import StreamingHttpResponse
from personal_center.sql_file import select_mysql, topic_directory as directory, create_excel, document_echarts, \
    document_pdf
from administrative.models import VehicleApply, Vehicle, VehicleAuditRecord, VehicleUseInfo, Topics, Company, \
    Topicsattachments, ConferenceMemo, OfficialDocuments, Driver, Sequence, TopicsAuditRecord, \
    OfficialDocumentsAuditRecord, Correspondence, CorrespondenceRecord, CorrespondencePeople, ContractApproval
from Oa_system.models import Department, Staffing
from correspondence.models import InboxInfo, InboxInfoPeople, chatting_records, ChatGroups
from django.contrib.auth import login, authenticate, logout
from PyPDF2 import PdfFileMerger
from Administrative_office_system.settings import SECRET_KEY
from Administrative_office_system.utils.views import LoginRequiredMixin, GetGroupView
from personal_center.models import User, BillGroup, Group, ConferenceRoomApplication, SealApplyAuditRecord, SealApply, \
    SortLine, Scheduling, Product, AssetRegistration, RealTimeInventory, ProductPurchase, ProductPurchaseLine, \
    AuditForm, ProductPurchaseAuditRecord, StockManage, StockManageLine, ProductAdopt, ProductAdoptLine, \
    ProductAdoptAuditRecord, seal, FixedAssets, FixedAssetsAuditRecord, SealApplyNumber, MakeCopy, ConferenceRoomSignee
import re, json, base64, os, uuid
from operator import attrgetter
import jwt
from itertools import chain
from django.db.models import Q, Count
from django.utils.encoding import escape_uri_path
from personal_center.creat_excel import create_table
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_job
from chinese_calendar import is_workday
from personal_center.process_check import Jeremy_levin_preview, my_shouwen
from personal_center.sql_file import manage_flow
from administrative.models import ConferenceMemoAuditRecord
from PyPDF2 import PdfFileReader
from logistics.MessagePushOperationRecords import RecordAndPush

# 开启定时工作
from system_setup.models import CustomerForm, CustomerFormModule, LowCodeBill
from system_setup.utils import deal_process_html

def deal_templates_html(html):
    html = urllib.parse.unquote(base64.b64decode(html).decode())
    soup = BeautifulSoup(html, 'lxml')
    input_strs = soup.findAll(['input', 'select', 'textarea'])
    record_list = []
    for input_str in input_strs:
        if input_str.get('type') == 'radio':
            record_list.append({"id": input_str.get('id', ''), "type": input_str.get('type'), "name": "radio_button"})
        else:
            record_list.append({"id": input_str.get('id', ''), "type": input_str.get('type')})

    return record_list

try:
    # 实例化调度器
    scheduler = BackgroundScheduler(timezone='Asia/Shanghai')

    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")


    # 设置定时任务，选择方式为interval，时间间隔为10s
    # 另一种方式为每天固定时间执行任务，对应代码为：
    @register_job(scheduler, 'cron', hour=19, minute=30, id='task_time', replace_existing=True, misfire_grace_time=300)
    # @register_job(scheduler,"interval", seconds=30,replace_existing=True)
    def my_job():
        # 这里写你要执行的任务
        now = datetime.now()
        # now = datetime.strptime('2022-07-03', '%Y-%m-%d')

        if now.weekday() == 6:
            sql = ''' update personal_center_sortline set is_deleted = TRUE where is_deleted = FALSE '''
            with connection.cursor() as cursor:
                cursor.execute(sql)

            one_line_list, two_line_list = scheduling_fun(now)
            for i in one_line_list:
                SortLine.objects.create(type="1", date=i[2], day_type=i[0], user_id=i[1], is_deleted=False)
            for t in two_line_list:
                SortLine.objects.create(type="2", date=t[2], day_type=t[0], user_id=t[1], is_deleted=False)
    # scheduler.start()
except Exception as e:
    print(e)
    # 有错误就停止定时器
    # scheduler.shutdown()


def scheduling_fun(now):
    one_line_list = []
    two_line_list = []
    day_off_number = 0
    work_number = 1
    # ******************************************************** 一线班 ********************************************************
    while work_number < 8:
        monday = now + timedelta(days=work_number)

        if is_workday(monday):
            limit_number = 1
        else:
            limit_number = 2
            day_off_number += 1

        select_sql = f"SELECT A.id, A.day_type, A.user_id, B.real_name FROM personal_center_scheduling A LEFT JOIN tb_users_message B ON A.user_id=B.id WHERE A.type=1 AND A.is_work=0 ORDER BY A.id ASC LIMIT {limit_number}"
        try:
            with connection.cursor() as cursor:
                cursor.execute(select_sql)
                all_data = list(cursor.fetchall())
            if all_data:
                one_list, two_list = [], []
                if len(all_data) < limit_number:
                    updata_sql = f"UPDATE personal_center_scheduling SET is_work=0 WHERE id < {all_data[-1][0]}"
                    with connection.cursor() as cursor:
                        cursor.execute(updata_sql)

                    select_sql = f"SELECT A.id, A.day_type, A.user_id, B.real_name FROM personal_center_scheduling A LEFT JOIN tb_users_message B ON A.user_id=B.id WHERE A.type=1 AND A.is_work=0 ORDER BY A.id ASC LIMIT {limit_number - len(all_data)}"
                    with connection.cursor() as cursor:
                        cursor.execute(select_sql)
                        all_data1 = list(cursor.fetchall())
                        all_data = all_data + all_data1

                work_type, people_name, work_type1, people_name1 = "", "", "", ""
                if len(all_data) == 1:
                    work_type = 'b'
                    people_name = all_data[0][2]
                    one_list.append(work_type)
                    one_list.append(people_name)
                    one_list.append(monday)
                    one_line_list.append(one_list)
                else:
                    if all_data[0][1] == "a" and all_data[1][1] == "b":
                        work_type = "b"
                        people_name = all_data[0][2]
                        work_type1 = "a"
                        people_name1 = all_data[1][2]
                    elif all_data[0][1] == "b" and all_data[1][1] == "a":
                        work_type = "a"
                        people_name = all_data[0][2]
                        work_type1 = "b"
                        people_name1 = all_data[1][2]
                    else:
                        work_type = "a"
                        people_name = all_data[0][2]
                        work_type1 = "b"
                        people_name1 = all_data[1][2]
                    one_list.append(work_type), one_list.append(people_name), one_list.append(monday)
                    two_list.append(work_type1), two_list.append(people_name1), two_list.append(monday)
                    one_line_list.append(one_list), one_line_list.append(two_list)

                if len(all_data) == 1:
                    updata_sql1 = f"UPDATE personal_center_scheduling SET is_work=1, day_type='{work_type}' WHERE id={all_data[0][0]}"
                    with connection.cursor() as cursor:
                        cursor.execute(updata_sql1)
                else:
                    for t in range(2):
                        if t == 1:
                            updata_sql1 = f"UPDATE personal_center_scheduling SET is_work=1, day_type='{work_type}' WHERE id={all_data[0][0]}"
                        else:
                            updata_sql1 = f"UPDATE personal_center_scheduling SET is_work=1, day_type='{work_type1}' WHERE id={all_data[1][0]}"
                        with connection.cursor() as cursor:
                            cursor.execute(updata_sql1)
                work_number += 1

            else:
                updata_sql = "UPDATE personal_center_scheduling SET is_work=0 WHERE type=1"
                with connection.cursor() as cursor:
                    cursor.execute(updata_sql)

        except Exception as E:
            print("查询数据出错：", E)

    # ******************************************************** 二线班 ********************************************************
    two_line_sql = f"SELECT A.id, A.day_type, A.user_id, B.real_name FROM personal_center_scheduling A LEFT JOIN tb_users_message B ON A.user_id=B.id WHERE A.type=2 ORDER BY A.id ASC"
    with connection.cursor() as cursor:
        cursor.execute(two_line_sql)
        two_line_data = cursor.fetchall()

    index_number = 0
    for two in two_line_data:
        if two[1] == 'b':
            index_number = two_line_data.index(two)
    rest_number = index_number + 1
    if rest_number > 4:
        rest_number = 0

    work_number = 1
    while work_number < 8:
        monday = now + timedelta(days=work_number)
        if is_workday(monday):  # 工作日
            two_line_people_name = two_line_data[rest_number][2]
            two_line_updata_sql = f"UPDATE personal_center_scheduling SET day_type='a' WHERE id={two_line_data[rest_number][0]}"

        else:  # 休息日
            two_line_people_name = two_line_data[rest_number][2]
            two_line_updata_sql = f"UPDATE personal_center_scheduling SET day_type='b' WHERE id={two_line_data[rest_number][0]}"

        rest_number += 1
        if rest_number > 4:
            rest_number = 0

        with connection.cursor() as cursor:
            cursor.execute(two_line_updata_sql)
        two_line_list.append(['b', two_line_people_name, monday])
        work_number += 1
    return one_line_list, two_line_list


class my_test(View):
    def get(self, request):
        # returnDict = {'code': 200, 'message': 'success', 'url': "/personal-center/my_test.html", "type": '1', "real_name": request.user.real_name, "job_number": request.user.job_number}
        returnDict = {'code': 200, 'message': 'success', 'url': "/personal-center/my_test.html", "type": '1', "real_name": "李可军", "job_number": '8101', "id": 118}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



def search_prople_DZ(job_number):
    """查询党政办公室人员工号, 查询是否是普通职员"""
    data_quer = User.objects.filter(
        Q(department="医院办公室") | Q(department="党委办公室") | Q(level=1) | Q(level=2) | Q(level=4))
    job_number_list = []
    for i in data_quer:
        job_number_list.append(i.job_number)
    if job_number in job_number_list:
        return True
    else:
        return False

class NoticeMessge(View):
    def get(self, request):
        sql = """
        SELECT
        u.mobile,
        a.document_number as number,
        'gw' as type 
        FROM administrative_conferencememo a
        INNER JOIN administrative_conferencememopeople b on a.id = b.notice_id_id
        INNER JOIN tb_users_message u on u.id = b.audit_people_id
        WHERE a.type not in ('e') and b.state = 'accept' and u.is_delete = false 
        
        UNION 
        
        SELECT
        u.mobile,
        a.recive_number as number,
        'lw' as type 
        FROM administrative_officialdocuments a
        INNER JOIN administrative_officialdocumentspeople b on b.notice_id_id = a.id
        INNER JOIN tb_users_message u on u.id = b.audit_people_id 
        WHERE b.state = 'accept' and u.is_delete = false 
        
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
        # mobiles = []
        record_list = []
        record_dict = {}
        for row in rows:
            if row[0] in record_dict:
                record_dict[row[0]].append({row[2]:row[1]})
            else:
                record_dict[row[0]] = [{row[2]:row[1]}]
        for k, v in record_dict.items():
            # for v1 in v:
            record_list.append({'mobile': k, 'gw_number_list': [v1['gw'] for v1 in v if 'gw' in v1], 'lw_number_list': [v1['lw'] for v1 in v if 'lw' in v1]})
        for record in record_list:
            gw_str = ''
            lw_str = ''
            if len(record['gw_number_list']) > 0:
                gw_number_str = ', '.join(record['gw_number_list'])
                gw_str = "待收阅的公文需要处理[%(gw_number_str)s], (共%(num)s条)，" % {'gw_number_str': gw_number_str,
                                                                          'num': len(record['gw_number_list'])}
            if len(record['lw_number_list']) > 0:
                lw_number_str = ', '.join(record['lw_number_list'])
                lw_str = "待收阅的上级来文需要处理[%(lw_number_str)s], (共%(num)s条)，" % {'lw_number_str': lw_number_str,
                                                                            'num': len(record['lw_number_list'])}
            mssage_str = '您有%(gw_str)s%(lw_str)s请登录OA系统（网址：http://192.168.60.200:8000/）在“流程管理—我的待办”中收阅文件。另外在“我的收文”中可以查阅我已经收阅的所有文件。' % {
                'gw_str': gw_str, 'lw_str': lw_str}
            send_mssage([record['mobile']],mssage_str)
        returnDict = {'code': 200, 'message': 'ok！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")
    # mobiles = list(set(mobiles))
    # send_mssage(mobiles, "您有待收阅的公文要处理！请登录OA系统在我的收文里面查看。")


def notice_messge():
    """
    [{"mobile": "17786431727", "gw_number_list": ["会议纪要〔2022〕1号", "会议纪要〔2022〕2号"], "lw_number_list": ["2022-09-21-2"]}]

    """
    sql = '''
    SELECT
    u.mobile,
    a.document_number as number 
    FROM administrative_conferencememo a
    INNER JOIN administrative_conferencememopeople b on a.id = b.notice_id_id
    INNER JOIN tb_users_message u on u.id = b.audit_people_id
    WHERE a.type not in ('e') and b.state = 'accept' and u.is_delete = false 
    
    UNION 
    
    SELECT
    u.mobile,
    a.recive_number as number
    FROM administrative_officialdocuments a
	INNER JOIN administrative_officialdocumentspeople b on b.notice_id_id = a.id
    INNER JOIN tb_users_message u on u.id = b.audit_people_id 
    WHERE b.state = 'accept' and u.is_delete = false 
    '''
    with connection.cursor() as cursor:
        cursor.execute(sql)
        rows = cursor.fetchall()
    mobiles = []
    record_list = []
    # for row in rows:
    #     record_list.append({})
        # if row[0]
    # for row in rows:
    #     mobiles.append(row[0])
    # mobiles = list(set(mobiles))
    # if len(mobiles) > 0:
    #     send_mssage(mobiles,
    #                 "您有待收阅的公文需要处理，请登录OA系统（网址：http://192.168.60.200:8000/）在“流程管理—我的待办”中收阅文件。另外在“我的收文”中可以查阅我已经收阅的所有文件。")


class base(View):
    def get(self, request):
        return render(request, 'personal_center/base.html')


class home(View):
    def get(self, request):
        try:
            real_names = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        # 上次登录时间
        last_loginTime = str(request.user.last_login).split(".")[0]

        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 这里获得代理ip

        myaddr = ip
        addr_str = '中国 湖北省 荆门市 京山市'

        meet_room_obj = ConferenceRoomApplication.objects.filter(
                statr_time__gte=time.strftime(f"%Y-%m-%d 00:00:00", time.localtime()),
                end_time__lte=time.strftime(f"%Y-%m-%d 23:59:59", time.localtime()),
                status__in=[1, 2, 0], state='audit')

        head_portrait = "/media/" + str(request.user.head_portrait)
        if head_portrait == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait):
            head_portrait = "/static/personal_center/img/default.jpeg"

        objs = request.user.votingpeopletable_set.all()
        background_flag, content = False, ""
        for obj in objs:
            now_timestamp = time.time()
            end_timestamp = str_to_timestamp(obj.voting_id.vote_deadline, '%Y-%m-%d')
            if not obj.voting_option.all().count() and (now_timestamp - end_timestamp < 0):
                background_flag = True
                content = obj.voting_id.vote_content
                break

        survey_flag, survey_content = False, ''
        survey_obj = request.user.questionnairepeople_set.all()
        for sur in survey_obj:
            now_timestamp = time.time()
            end_timestamp = str_to_timestamp(sur.survey_id.survey_id.end_time, '%Y-%m-%d')
            RecordObj = QuestionnaireRecord.objects.filter(parent_id=sur.survey_id)
            if not RecordObj.all().count() and (now_timestamp - end_timestamp < 0):
                survey_flag = True
                survey_content = sur.survey_id.survey_id.illustrate
                break

        morals_wind_flag = False
        eva_obj = request.user.evaluationopinion_set.filter(node="one", state="unaudit")
        if eva_obj.count():
            morals_wind_flag = True

        MeetRoomObj = ConferenceRoomSignee.objects.filter(SigneeCode=request.user, parent_id__status__in=['0', '1'])
        meet_room_list = []
        for room in MeetRoomObj:
            meet_room_list.append({"particulars": room.parent_id.particulars, "meeting_root": room.parent_id.meeting_root, "flow_id": room.parent_id.id, 'apply_user': room.parent_id.names})

        return render(request, 'personal_center/home.html', {'realname': real_names, 'position': position, 'department': department, "remarks": request.user.remarks, "background_flag": background_flag, "morals_wind_flag": morals_wind_flag, "job_number": request.user.job_number,
                     "last_loginTime": last_loginTime, "myaddr": myaddr, "addr_str": addr_str, "head_portrait": head_portrait, "meet_room_obj": meet_room_obj, "content": content, "survey_flag": survey_flag, "survey_content": survey_content, 'meet_room_list': meet_room_list})


# 登录
class signin(View):
    def get(self, request):
        username = request.COOKIES.get("username", None)
        pwd = request.COOKIES.get("pwd", None)
        userId = request.GET.get('userId', None)
        if userId:
            user = User.objects.get(username=userId)
            request.user = user
            login(request, user)
            return redirect('/personal-center/home.html')
        if username and pwd:
            return render(request, 'personal_center/sign-in.html', {"username": username, "pwd": pwd})
        return render(request, 'personal_center/sign-in.html')

    def post(self, request):
        username = request.POST.get("username", None)
        password = request.POST.get("pwd", None)
        remembered = request.POST.get("remembered", None)
        platform = request.POST.get("platform", None)
        login_type = request.POST.get("login_type", "admin")
        validate = request.POST.get("validate", "")
        print('username:', username)
        print('password:', password)
        print('remembered:', remembered)
        print('platform:', platform)

        if login_type == "user" and username == "admin":
            returnDict = {'code': 400, 'message': '用户端无法登录管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        verification_code = request.session.get('verification_code', '')
        session_time = request.session.get('session_time', '')
        if login_type == "admin":
            now_time = time.time()
            if now_time - float(session_time) > 60:
                returnDict = {'code': 400, 'message': '动态验证码已失效，请重新获取！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if verification_code != validate:
                returnDict = {'code': 400, 'message': '动态验证码输入错误，请重新输入！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        print("===============================verification_code: ", verification_code)
        print("===============================session_time: ", session_time)

        # 2.校验
        if not username:
            returnDict = {'code': 400, 'message': '用户名不能为空！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        elif not password:
            returnDict = {'code': 400, 'message': '密码不能为空！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # 3.验证是否能够登录
        user = authenticate(username=username, password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            returnDict = {'code': 400, 'message': '用户名或者密码错误！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if user.is_delete == 1:
            returnDict = {'code': 400, 'message': '由于您长期未登录系统，账号已经冻结；如需账号恢复到正常情况，请联系管理员解决！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if platform:
            if platform == 'web':
                # 4.状态保持
                login(request, user)

                # 5.判断是否记住用户
                if remembered != 'true':
                    # 7.如果没有记住: 关闭立刻失效
                    request.session.set_expiry(0)
                else:
                    request.session.set_expiry(None)

        user_dict = {
            'exp': datetime.utcnow() + timedelta(days=14),
            'iat': datetime.utcnow(),
            'username': user.username,
            'real_name': user.real_name,
            'now_time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}
        encoded_jwt = jwt.encode(user_dict, SECRET_KEY, algorithm='HS256')
        print('user_dict', user_dict)
        print('encoded_jwt', encoded_jwt)

        head_portrait = "/media/" + str(user.head_portrait)
        if head_portrait == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait):
            head_portrait = "/static/personal_center/img/default.jpeg"
        returnDict = {'code': 200, 'message': '登陆成功！', 'data': {'token': encoded_jwt}, 'username': user.username, "real_name": user.real_name, "dep": user.company.name, "head_portrait": head_portrait}
        # print(returnDict)
        resp = HttpResponse(json.dumps(returnDict), content_type="application/json")
        resp.set_cookie('token', encoded_jwt)
        if remembered == 'true':
            resp.set_cookie('username', username)
            resp.set_cookie('pwd', password)
        return resp


# 退出登录
class signout(View):
    def get(self, request):
        logout(request)
        username = request.COOKIES.get("username", None)
        pwd = request.COOKIES.get("pwd", None)
        if username and pwd:
            return render(request, 'personal_center/sign-in.html', {"username": username, "pwd": pwd})
        return render(request, 'personal_center/sign-in.html')


def num_to_char(num):
    if num == 1:
        return '星期一'
    elif num == 2:
        return '星期二'
    elif num == 3:
        return '星期三'
    elif num == 4:
        return '星期四'
    elif num == 5:
        return '星期五'
    elif num == 6:
        return '星期六'
    else:
        return '星期日'


class page_not_found(View):
    def get(self, request):
        return render(request, "personal_center/404.html")


# 修改密码
class ChangePassword(View):
    def get(self, request):
        pass

    def post(self, request):
        old_password = request.POST.get('old_password')  # 旧密码
        new_password = request.POST.get('new_password')  # 新密码
        new_password2 = request.POST.get('new_password2')  # 新密码

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400, 'message': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code': 400, 'message': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{6,20}$', new_password):
            return http.JsonResponse({'code': 400, 'message': '密码最少6位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400, 'message': '两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'message': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        # # 响应密码修改结果：重定向到登录界面
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ResetPassword(View):
    def post(self, request):
        new_password = '123456'
        job_number = request.POST.get('job_number')  # 用户工号
        # 修改密码
        try:
            user = User.objects.get(job_number=job_number)
            user.set_password(new_password)
            user.save()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'message': '修改密码失败!请检查该用户工号！'})

        # 清理状态保持信息
        logout(request)

        # # 响应密码修改结果：重定向到登录界面
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BillGroupView(View):
    def get(self, request):
        page = request.GET.get("page", None)
        id = request.GET.get("id", None)
        executor = request.GET.get("executor", None)
        groups_get = request.GET.get("groups", None)
        chooseval = request.GET.get("chooseval", None)
        input_value = request.GET.get("input_value", None)
        if id:
            b = BillGroup.objects.get(id=int(id))
            if executor:
                executor = re.findall('\((.*?)\)', executor)
                b.apply_user = ', '.join(executor)
                apply_user_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in executor]
                apply_user_str = ', '.join(apply_user_list)
                b.apply_user_name = apply_user_str
                b.save()
                b.executor.clear()
                for i in [User.objects.get(job_number=user_str.strip()) for user_str in executor]:
                    b.executor.add(i)
            if groups_get:
                groups = groups_get.split(',')
                b.groups.clear()
                for group in groups:
                    temp = Group.objects.get(level=group.strip())
                    if temp:
                        b.groups.add(temp)

        if chooseval and input_value:
            if chooseval == '菜单':
                bill_groups = BillGroup.objects.filter(menu__contains=input_value)
            elif chooseval == '单据':
                bill_groups = BillGroup.objects.filter(bill__contains=input_value)
            elif chooseval == '可执行人':
                bill_groups = BillGroup.objects.filter(apply_user_name__contains=input_value)
            else:
                bill_groups = BillGroup.objects.all()
        else:
            bill_groups = BillGroup.objects.all()
        return_data = []
        for bill_group in bill_groups:
            groups = ', '.join([g.level for g in bill_group.groups.all()])
            return_data.append({
                'id': bill_group.id,
                'menu': bill_group.menu,
                'bill': bill_group.bill,
                'apply_user': bill_group.apply_user_name,
                'job_numbers': bill_group.apply_user,
                'groups': groups,
                'type': bill_group.get_type_display()
            })
        return HttpResponse(
            json.dumps({'count': len(return_data), 'bill_groups': return_data[(int(page) - 1) * 20:int(page) * 20]}),
            content_type="application/json")

    def post(self, request):
        menu = request.POST.get('menu')
        bill = request.POST.get('bill')
        apply_user = request.POST.get('apply_user', None)
        groups = request.POST.get('groups', None)
        apply_user = re.findall('\((.*?)\)', apply_user)
        # groups = ['C', 'D']
        # try:
        b = BillGroup.objects.create(menu=menu, bill=bill, apply_user=', '.join(apply_user))
        if b.apply_user:
            bill_group_list = b.apply_user.split(', ')
            apply_user_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in bill_group_list]
            apply_user_str = ', '.join(apply_user_list)
            b.apply_user_name = apply_user_str
            b.save()
            for i in [User.objects.get(job_number=user_str.strip()) for user_str in bill_group_list]:
                b.executor.add(i)
        groups = groups.split(',')
        for group in groups:
            if group:
                temp = Group.objects.get(level=group.strip())
                if temp:
                    b.groups.add(temp)

        bill_groups = BillGroup.objects.all()
        return_data = []
        page = 1
        for bill_group in bill_groups:
            groups = ''
            for g in bill_group.groups.all():
                groups += g.level
            return_data.append({
                'id': bill_group.id,
                'menu': bill_group.menu,
                'bill': bill_group.bill,
                'apply_user': bill_group.apply_user_name,
                'job_numbers': bill_group.apply_user,
                'groups': groups
            })
        returnDict = {'code': 200, 'message': 'success', 'count': len(return_data),
                      'bill_groups': return_data[(int(page) - 1) * 20:int(page) * 20]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BillGroupWriteView(View):
    def post(self, request):
        id = request.POST.get('id')
        bill = request.POST.get('bill', None)
        apply_user = request.POST.get('apply_user', None)
        groups = request.POST.get('groups', None)
        menu = request.POST.get('menu', None)
        try:
            bill_group = BillGroup.objects.get(id=id)
            if bill:
                bill_group.bill = bill
            if apply_user:
                bill_group.apply_user = apply_user
            if groups:
                bill_group.groups.clear()
                for group in groups:
                    temp = Group.objects.get(level=group)
                    if temp:
                        bill_group.groups.add(temp)
            if menu:
                bill_group.menu = menu
            bill_group.save()
        except Exception as e:
            return http.JsonResponse({'code': 500, 'message': '修改失败'})
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GetBillGroupView(View):
    def get(self, request):
        menu = request.GET.get('menu', None)
        dic = {}
        if menu:
            dic = GetGroupView(menu, request.user)
        returnDict = {'code': 200, 'message': 'success', 'dic': dic}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 流程发起
class sponsor(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
            customer_form_dict = {}
            customer_form_objs = CustomerForm.objects.filter(abandoned='0')
            for customer_form_obj in customer_form_objs:
                if customer_form_obj.module in customer_form_dict:
                    customer_form_dict[customer_form_obj.module].append(
                        {'id': customer_form_obj.id, 'name': customer_form_obj.name})
                else:
                    customer_form_dict[customer_form_obj.module] = [
                        {'id': customer_form_obj.id, 'name': customer_form_obj.name}]
        except:
            return redirect("/")

        group_id = request.user.group.id
        ydyf_count = Staffing.objects.filter(station='医德医风考核人', post_personnel=request.user).count()
        ydyf_flag = 'false'
        if ydyf_count:
            ydyf_flag = 'true'

        PartyOfficeFlag = 'false'
        if request.user.company.id == 3:
            PartyOfficeFlag = 'true'

        return render(request, "personal_center/sponsor.html",
                      {'realname': real_name, 'position': position, 'department': department, 'group_id': group_id, "ydyf_flag": ydyf_flag, "PartyOfficeFlag": PartyOfficeFlag,
                       "customer_form_dict": customer_form_dict, 'xianyou_list': [i.name for i in CustomerFormModule.objects.all()]})


def str_time(timeStr):
    return time.mktime(time.strptime(timeStr, '%Y-%m-%d %H:%M:%S'))


class room_reservation(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        apply = request.GET.get("apply", 'false')
        page = request.GET.get("page", 1)
        search_date = request.GET.get("date", '')
        search_type = request.GET.get("search", None)
        select_data = ConferenceRoomApplication.objects.filter(status__in=['0', '1'], state='audit').order_by("statr_time")
        now_time = datetime.now()
        flag, name_list, particulars, meeting_adress, meeting_prople, meeting_time_day, meeting_time_start, meeting_time_end = True, [], "", "", "", "", "", ""

        for select in select_data:
            if select.status == "3":
                continue
            if select.statr_time < now_time and select.end_time > now_time:
                status = "1"
            elif now_time < select.statr_time:
                status = '0'
            elif now_time > select.end_time:
                status = "2"
            else:
                status = "2"

            if len(json.loads(select.conferee)) > 1:
                if (request.user.job_number in json.loads(select.conferee)[1]) or request.user.real_name == select.conferee:
                    if flag:
                        particulars = select.particulars
                        meeting_adress = select.meeting_root
                        meeting_prople = select.names
                        meeting_time_day = str(select.statr_time).split(" ")[0]
                        meeting_time_start = str(select.statr_time).split(" ")[1][:-3]
                        meeting_time_end = str(select.end_time).split(" ")[1][:-3]
                        name_list = json.loads(select.conferee)[0]
                        flag = False
            select.status = status
            select.save()

        all_data = ConferenceRoomApplication.objects.filter(names=real_name, department=department).order_by("-id")
        all_data_list = []
        for tt in all_data[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = tt.id
            one_dict["name"] = tt.names
            one_dict["department"] = tt.department
            one_dict["particular"] = tt.particulars
            one_dict["start_time"] = str(tt.statr_time)[:-3]
            one_dict["end_time"] = str(tt.end_time)[:-3]
            one_dict["meeting_root"] = tt.meeting_root
            one_dict["state"] = tt.state
            one_dict["status"] = tt.status
            one_dict["audit_note"] = tt.audit_note
            one_dict["audit_user"] = tt.audit_people.real_name if tt.audit_people else ''
            all_data_list.append(one_dict)

        if search_type:
            returnData = {"code": 200, "status": "success", "all_data_list": all_data_list,
                          "all_data_count": all_data.count()}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        if search_date:
            HourStatrTime = f"{search_date} 00:00"
            HourEndTime = f"{search_date} 23:00"
        else:
            HourStatrTime = time.strftime("%Y-%m-%d 00:00", time.localtime())
            HourEndTime = time.strftime("%Y-%m-%d 23:00", time.localtime())

        data_list = []
        today_data_start = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=HourStatrTime,
            hour_end_time__lte=HourEndTime,
            status__in=[1, 2, 0], state='audit').order_by("hour_statr_time")

        today_data_end = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=HourStatrTime,
            hour_end_time__lte=HourEndTime,
            status__in=[1, 2, 0], state='audit').order_by("-hour_end_time")

        start_hour, end_hour = 5, 22
        if today_data_start:
            if int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0]) < start_hour:
                start_hour = int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0])
        if today_data_end:
            if int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0]) > end_hour:
                end_hour = int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0])

        for i in range(start_hour, end_hour):
            start_times = "0" + str(i) + ":00" if i < 10 else str(i) + ":00"
            end_times = "0" + str(i + 1) + ":00" if i + 1 < 10 else str(i + 1) + ":00"
            one_list = {'time_duan': start_times + " ~ " + end_times, }
            one_dict = {}
            room_list = ["行政楼七楼大会议室", "小会议室", "党员活动室", "内科楼十楼会议室"]
            for t in range(4):
                if search_date:
                    HourStatrTimeStr = f"{search_date} {start_times.split(':')[0]}:00"
                    HourEndTimeStr = f"{search_date} {end_times.split(':')[0]}:00"
                else:
                    HourStatrTimeStr = time.strftime(f"%Y-%m-%d {start_times.split(':')[0]}:00", time.localtime())
                    HourEndTimeStr = time.strftime(f"%Y-%m-%d {end_times.split(':')[0]}:00", time.localtime())
                room_data = ConferenceRoomApplication.objects.filter(
                    hour_statr_time__lte=HourStatrTimeStr,
                    hour_end_time__gte=HourEndTimeStr,
                    status__in=[1, 2, 0], meeting_root=room_list[t], state='audit')

                if room_data:
                    if HourStatrTimeStr == str(room_data[0].hour_statr_time)[:16]:
                        one_list[f'status_{t}'] = room_data[0].status
                        content_str = "使用科室：" + room_data[0].department + "<br>" + "会议时间：" + \
                                      str(room_data[0].statr_time).split(" ")[1][:-3] + " ~ " + \
                                      str(room_data[0].end_time).split(" ")[1][:-3] + "<br>" + "会议事由：" + room_data[
                                          0].particulars + "<br>" + "参会人数：" + room_data[
                                          0].Number_people + "<br>" + "申请人：" + room_data[0].names
                        one_list[f'content_{t}'] = content_str
                        one_list[f'merge_{t}'] = int(str(room_data[0].hour_end_time).split(" ")[1].split(":")[0]) - int(
                            str(room_data[0].hour_statr_time).split(" ")[1].split(":")[0])
                else:
                    one_list[f'status_{t}'] = ''
                    one_list[f'content_{t}'] = ''
                    one_list[f'merge_{t}'] = 0
            one_dict['data'] = one_list
            data_list.append(one_dict)
        return render(request, "personal_center/room_reservation.html",
                      {'realname': real_name, 'position': position, 'department': department, "name_list": name_list,
                       "particulars": particulars, "meeting_adress": meeting_adress, "meeting_prople": meeting_prople,
                       "meeting_time_day": meeting_time_day, "meeting_time_start": meeting_time_start,
                       "meeting_time_end": meeting_time_end, "all_data_list": all_data_list, "uuid": uuid.uuid4(),
                       "all_data_count": all_data.count(), "room_data": data_list, "apply": apply, "search_date": search_date})

    def post(self, request):
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        names = request.POST.get('names', None)
        department = request.POST.get('department', None)
        particulars = request.POST.get('particulars', None)
        time_start = request.POST.get('time_start', None)
        time_end = request.POST.get('time_end', None)
        meeting_root = request.POST.get('meeting_root', None)
        Number_people = request.POST.get('Number_people', None)
        conferee = request.POST.get('conferee', None)
        fujian = request.POST.get('uuid', '')
        SignInCode = request.POST.get('SignInCode', '')
        if not SignInCode:
            returnData = {"code": 500, "message": "请选择是否生成签到二维码！"}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        RecordAndPush().OperationRecords(request, "会议室使用")
        if time_start < now_time:
            returnData = {"code": 500, "message": "会议室只能预定当前时间之后！"}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        history_objs = ConferenceRoomApplication.objects.filter(
            Q(statr_time__lte=datetime.strptime(time_start, "%Y-%m-%d %H:%M:%S"),
              end_time__gte=datetime.strptime(time_end, "%Y-%m-%d %H:%M:%S")) |
            Q(statr_time__range=[datetime.strptime(time_start, "%Y-%m-%d %H:%M:%S") + timedelta(seconds=1),
                                 datetime.strptime(time_end, "%Y-%m-%d %H:%M:%S") + timedelta(seconds=-1)]) | Q(
                end_time__range=[datetime.strptime(time_start, "%Y-%m-%d %H:%M:%S") + timedelta(seconds=1),
                                 datetime.strptime(time_end, "%Y-%m-%d %H:%M:%S") + timedelta(seconds=-1)])).filter(
            state='audit',
            meeting_root=meeting_root)

        if history_objs.count() > 0:
            history_obj = history_objs.first()
            returnDict = {'code': 500, 'message': '该会议室在本时间段内(%s-%s)已被占用！' % (
                history_obj.statr_time.strftime("%Y-%m-%d %H:%M"), history_obj.end_time.strftime("%Y-%m-%d %H:%M"))}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        save_data, name_list, job_num = [], [], []
        try:
            confereeList = [i for i in conferee.split(",") if i]
            for tt in confereeList:
                tt_list = tt.split("(")
                name_list.append(tt_list[0])
                job_num.append(tt_list[1][:-1])
            save_data.append(name_list)
            save_data.append(job_num)
        except:
            save_data.append(conferee)
        hour_statr_time = time_start.split(" ")[0] + " " + time_start.split(" ")[1].split(":")[0] + ":00"
        hour_end_time = time_end
        if int(time_end.split(" ")[1][3:5]) > 0:
            hour_time = str((int(time_end.split(" ")[1][:2]) + 1)) if (int(time_end.split(" ")[1][:2]) + 1) > 9 else (
                        "0" + str((int(time_end.split(" ")[1][:2]) + 1)))
            hour_end_time = time_end.split(" ")[0] + " " + hour_time + ":00"
        com_obj = Company.objects.get(id=80)
        room_obj = ConferenceRoomApplication.objects.create(names=names, department=department, particulars=particulars, SignInCode=SignInCode,
                                                 statr_time=time_start, end_time=time_end, meeting_root=meeting_root, apply_user=request.user,
                                                 Number_people=Number_people, conferee=json.dumps(save_data),
                                                 hour_statr_time=hour_statr_time, hour_end_time=hour_end_time,
                                                 state='unaudit', audit_people=com_obj.head_people, uuid=fujian)

        if SignInCode == "1":
            file_path = os.path.join(os.getcwd(), f'static/personal_center/list_attendees/{uuid.uuid4()}')
            myFiles = request.FILES.get('PersonnelList', None)
            read_file = xlrd.open_workbook(filename=None, file_contents=myFiles.read())
            file_table = read_file.sheets()[0]
            file_table_rows = file_table.nrows
            for t in range(1, file_table_rows):
                ConferenceRoomSignee.objects.create(parent_id=room_obj, SigneeCode=User.objects.get(real_name=file_table.cell(t, 0).value, job_number=int(file_table.cell(t, 1).value)))

        topic_type = "会议室"
        applicant = names
        ApplicationTime = datetime.now().strftime("%Y-%m-%d %H:%M")
        SubjectMatter = particulars[:15] + "……" if len(particulars) > 15 else particulars
        try:
            RecordAndPush().MessagePush(com_obj.head_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        except:
            pass
        returnData = {"code": 200, "status": "success", "audit_user": com_obj.head_people.real_name, "message": "预定申请成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class room_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "personal_center/room_list.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = ConferenceRoomApplication.objects.filter(Q(particulars__contains=search_data) | Q(meeting_root__contains=search_data), names=request.user.real_name).order_by('-create_time')
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if obj.get_state_display() != "结束":
                status = obj.get_state_display()
            else:
                status = "未开始" if obj.status == "0" else "进行中" if obj.status == "1" else "结束" if obj.status == "2" else "撤回"
            data_list.append(
                {'id': obj.id, 'particular': obj.particulars, 'room_name': obj.meeting_root, 'current_audit_user': obj.audit_people.real_name if obj.audit_people else "",
                 'state': status, 'start_time': obj.statr_time.strftime("%Y-%m-%d %H:%M"), 'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M")}
            )
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class room_detail(View):
    def post(self, request):
        """
        __gte 大于等于
        __lte 小于等于
        """
        search_time = request.POST.get("search_time", '')  # 查询时间
        data_list = []
        today_data_start = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=time.strftime(f"{search_time} 00:00"),
            hour_end_time__lte=time.strftime(f"{search_time} 23:00"),
            status__in=[1, 2, 0], state='audit').order_by("hour_statr_time")

        today_data_end = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=time.strftime(f"{search_time} 00:00"),
            hour_end_time__lte=time.strftime(f"{search_time} 23:00"),
            status__in=[1, 2, 0], state='audit').order_by("-hour_end_time")

        start_hour, end_hour = 5, 22
        if today_data_start:
            if int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0]) < start_hour:
                start_hour = int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0])
        if today_data_end:
            if int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0]) > end_hour:
                end_hour = int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0])

        for i in range(start_hour, end_hour):
            start_times = "0" + str(i) + ":00" if i < 10 else str(i) + ":00"
            end_times = "0" + str(i + 1) + ":00" if i + 1 < 10 else str(i + 1) + ":00"
            one_list = {'time_duan': start_times + " ~ " + end_times, }
            one_dict = {}
            room_list = ["行政楼七楼大会议室", "小会议室", "党员活动室", "内科楼十楼会议室"]
            for t in range(4):
                room_data = ConferenceRoomApplication.objects.filter(
                    hour_statr_time__lte=time.strftime(f"{search_time} {start_times}"),
                    hour_end_time__gte=time.strftime(f"{search_time} {end_times}"),
                    status__in=[1, 2, 0], meeting_root=room_list[t], state='audit')

                if room_data:
                    if str(time.strftime(f"{search_time} {start_times}")) == str(room_data[0].hour_statr_time)[:16]:
                        one_list[f'status_{t}'] = room_data[0].status
                        content_str = "使用科室：" + room_data[0].department + "<br>" + "会议时间：" + \
                                      str(room_data[0].statr_time).split(" ")[1][:-3] + " ~ " + \
                                      str(room_data[0].end_time).split(" ")[1][:-3] + "<br>" + "会议事由：" + room_data[
                                          0].particulars + "<br>" + "参会人数：" + room_data[
                                          0].Number_people + "<br>" + "申请人：" + room_data[0].names
                        one_list[f'content_{t}'] = content_str
                        one_list[f'merge_{t}'] = int(str(room_data[0].hour_end_time).split(" ")[1].split(":")[0]) - int(str(room_data[0].hour_statr_time).split(" ")[1].split(":")[0])
                else:
                    one_list[f'status_{t}'] = ''
                    one_list[f'content_{t}'] = ''
                    one_list[f'merge_{t}'] = 0
            one_dict['data'] = one_list
            data_list.append(one_dict)
        returnData = {"code": 200, "status": "success", "data": data_list, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class room_recall(View):
    def post(self, request):
        room_id = request.POST.get("id", None)
        room_obj = ConferenceRoomApplication.objects.get(id=room_id)
        room_obj.status = '3'
        room_obj.audit_people = None
        room_obj.state = 'revoke'
        room_obj.save()
        all_data = ConferenceRoomApplication.objects.filter(names=request.user.real_name,
                                                            department=request.user.company.name).order_by("-id")
        all_data_list = []
        # for tt in all_data:
        #     one_dict = {}
        #     one_dict["name"] = tt.names
        #     one_dict["department"] = tt.department
        #     one_dict["particular"] = tt.particulars
        #     one_dict["start_time"] = str(tt.statr_time)[:-3]
        #     one_dict["end_time"] = str(tt.end_time)[:-3]
        #     one_dict["meeting_root"] = tt.meeting_root
        #     one_dict["status"] = tt.status
        #     all_data_list.append(one_dict)
        returnData = {"code": 200, "status": "success", "data": all_data_list, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceRoomAuditList(View):
    def get(self, request):
        user = request.user
        context = {'realname': request.user.real_name, 'position': request.user.post}
        return render(request, 'personal_center/conference_room_application.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = ConferenceRoomApplication.objects.filter(
            Q(audit_people=user) | Q(audit_users_already__in=[user]), status__in=['0', '1', '2']).order_by(
            '-create_time')
        data_list = [{'id': obj.id,
                      'names': obj.names,
                      'department': obj.department,
                      'particulars': obj.particulars,
                      'statr_time': obj.statr_time.strftime("%Y-%m-%d %H:%M"),
                      'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M"),
                      'meeting_root': obj.meeting_root,
                      'Number_people': obj.Number_people,
                      'state': obj.get_state_display(),
                      'audit_people': obj.audit_people.real_name if obj.audit_people else '',
                      'audit_note': obj.audit_note}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ConferenceRoomAudit(View):
    def post(self, request):
        id = request.POST.get("id", None)
        obj = ConferenceRoomApplication.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "会议室审核")
        except:
            pass
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请传state参数！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        if state == 'audit':
            ContainAllObj = ConferenceRoomApplication.objects.filter(statr_time__lte=obj.statr_time, end_time__gte=obj.end_time, meeting_root=obj.meeting_root, state="audit").count()         # 小于当前流程开始时间、大于结束时间
            if ContainAllObj:
                returnDict = {'code': 500, 'message': '该会议室在本时间段内已被占用！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            ContainStartObj = ConferenceRoomApplication.objects.filter(statr_time__lte=obj.statr_time, end_time__gte=obj.statr_time, meeting_root=obj.meeting_root, state="audit").count()      # 小于或等于当前流程开始时间，大于或等于当前流程的开始时间
            if ContainStartObj:
                returnDict = {'code': 500, 'message': '该会议室在本时间段内已被占用！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            ContainEndObj = ConferenceRoomApplication.objects.filter(statr_time__lte=obj.end_time, end_time__gte=obj.end_time, meeting_root=obj.meeting_root, state="audit").count()  # 小于或等于当前流程结束时间，大于或等于当前流程的结束时间
            if ContainEndObj:
                returnDict = {'code': 500, 'message': '该会议室在本时间段内已被占用！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            ContainEndObj = ConferenceRoomApplication.objects.filter(statr_time__gte=obj.statr_time, end_time__lte=obj.end_time, meeting_root=obj.meeting_root, state="audit").count()  # 大于或等于当前流程开始时间，小于或等于当前流程的结束时间
            if ContainEndObj:
                returnDict = {'code': 500, 'message': '该会议室在本时间段内已被占用！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = state
        obj.audit_note = audit_note
        obj.audit_people = None
        obj.save()
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ConferenceRoomDetail(View):
    def get(self, request):
        id = request.GET.get("id")
        obj = ConferenceRoomApplication.objects.get(id=int(id))
        history_list_objs = ConferenceRoomApplication.objects.filter(statr_time__range=(f"{obj.statr_time.strftime('%Y-%m-%d')} 00:00:00", f"{obj.end_time.strftime('%Y-%m-%d')} 23:59:59"), meeting_root=obj.meeting_root, status__in=['0', '1', '2']).order_by('create_time')
        history_list, conflict_list, not_conflict_list = [], [], []
        for i in history_list_objs:
            if i.state != 'unaudit':
                conflict = '1'
            else:
                clash_obj = ConferenceRoomApplication.objects.filter(Q(statr_time__lte=i.statr_time, end_time__gte=i.statr_time) | Q(statr_time__lte=i.end_time, end_time__gte=i.end_time), ~Q(id=obj.id), meeting_root=obj.meeting_root, status__in=['0', '1', '2'], state="audit")
                if clash_obj.count() >= 2:
                    conflict = '2'
                else:
                    if clash_obj.count() == 0:
                        conflict = '3'
                    else:
                        if i.statr_time >= obj.statr_time and i.end_time <= obj.end_time:
                            conflict = '2'
                        elif i.statr_time <= obj.statr_time and i.end_time >= obj.end_time:
                            conflict = '2'
                        elif i.statr_time <= obj.statr_time and i.end_time <= obj.end_time and i.end_time >= obj.statr_time:
                            conflict = '2'
                        elif i.statr_time >= obj.statr_time and i.end_time >= obj.end_time and i.statr_time <= obj.end_time:
                            conflict = '2'
                        else:
                           conflict = '3'
            one_dict = {"meeting_root": i.meeting_root, "create_time": i.create_time, "statr_time": i.statr_time, "end_time": i.end_time,
                             "status": i.status, "state": i.state, "id": i.id, "conflict": conflict, "names": i.names, "particulars": i.particulars, "SameTop": '1' if i.id == int(id) else '2'}
            if conflict == '2':
                conflict_list.append(one_dict)
            else:
                not_conflict_list.append(one_dict)

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.uuid)]
        history_list = conflict_list + not_conflict_list
        yb_objs = Company.objects.get(id=80).head_people.real_name
        SignDetailFlag = 'true' if obj.SignInCode == "1" and obj.state == 'audit' and request.user.real_name in [obj.names, yb_objs] else "false"
        ReceivingList = []
        LeaveOperator = 'true' if request.user.real_name == yb_objs else "false"
        for receiving in obj.conferenceroomsignee_set.filter(scan_or_not='1'):
            ReceivingList.append({"receiving": receiving.SigneeCode.real_name, "time": receiving.update_time.strftime("%Y-%m-%d %H:%M"),
                                  "signature_picture": '/media/' + str(receiving.SigneeCode.signature_picture) if receiving.SigneeCode.signature_picture else ''})
        context = {'obj': obj, 'realname': request.user.real_name, 'position': request.user.post, 'history_list_objs': history_list, 'signature_picture': str(obj.audit_users_already.all().first().signature_picture) if obj.audit_users_already.all().count() else "",
                   "file_list": file_list, "file_path": Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else "",
                   "sign_in_flag": 'true' if obj.SignInCode == "1" and obj.state=="audit" and datetime.now() < obj.end_time and request.user.real_name == obj.names else "false", "flow_id": id,
                   "register_flag": 'true' if obj.SignInCode == "1" and obj.state=="audit" else "false", "sing_people": ReceivingList, "SignDetailFlag": SignDetailFlag, 'LeaveOperator': LeaveOperator,
                   "is_audit": "true" if obj.state == 'unaudit' and request.user == obj.audit_people else 'false'}
        return render(request, 'personal_center/conference_room_detail.html', context)


class VehicleUseInfoView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'administrative/vehicle_reservation.html',
                      {"staff_level": request.user.level, "search_flag": "True", "panduan": "True", 'flag': True,
                       'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        # search_data = request.POST.get("search_data", None)  # 查询标题
        # tab = request.POST.get("tab", None)  # use 使用 apply 申请
        objs = user.vehicleapply_set.all().order_by('-create_time')
        data_list = [{
            # 'apply_user': obj.apply_user.real_name,
            'subject': obj.subject,
            'route': obj.route,
            'state': obj.get_state_str(),
            'id': obj.id,
            'current_audit_user': obj.current_audit_user.real_name if obj.current_audit_user else '',
            'start_time': obj.start_time.strftime("%Y-%m-%d %H:%M"),
            'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M"),
            'url': f"<a href='Vehicle_apply_detail.html?id={obj.id}'>查看</a>" if obj.state != 'stop' else f"<a href='Vehicle_apply_detail.html?id={obj.id}'>查看</a> | <a href='' id='{obj.id}' onclick='del_draft(this.id)' style='color:red;'>删除</a>",
        } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        # if tab == 'apply':
        #     objs = user.vehicleapply_set.all().order_by('-create_time')
        #     data_list = [{'apply_user': obj.apply_user.real_name,
        #                   'subject': obj.subject,
        #                   'route': obj.route,
        #                   'state': obj.get_state_display(),
        #                   'id': obj.id,
        #                   'current_audit_user': obj.current_audit_user.real_name,
        #                   'start_time': obj.start_time.strftime("%Y-%m-%d %H:%M"),
        #                   'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M")} for obj in
        #                  objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        # else:
        #     now_time = datetime.now().strftime("%Y-%m-%d")
        #     objs = VehicleUseInfo.objects.filter(start_time__gte=now_time)
        #     data_list = [{'registration_number': obj.vehicle.registration_number, 'driver': obj.driver,
        #                   'start_time': obj.start_time.strftime("%Y-%m-%d %H:%M"),
        #                   'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M"),
        #                   'seat': obj.vehicle.seat} for obj in
        #                  objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehiclePersonApply(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "administrative/vehicle_person_apply.html",
                      {'realname': real_name, 'position': position,
                       'department': department, "table_name": "administrative_vehicleapply"})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        # search_data = request.POST.get("search_data", None)  # 查询标题
        now_time = datetime.now().strftime("%Y-%m-%d")
        objs = VehicleUseInfo.objects.filter(start_time__gte=now_time, apply_id__state='cgb')
        data_list = [{'registration_number': obj.vehicle.registration_number,
                      'driver': obj.driver,
                      'start_time': obj.start_time.strftime("%Y-%m-%d %H:%M"),
                      'end_time': obj.end_time.strftime("%Y-%m-%d %H:%M"),
                      'seat': obj.vehicle.seat} for obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyIndex(View):
    def get(self, request):
        try:
            user = request.user
        except:
            return redirect("/")
        return render(request, 'administrative/car_apply_detail.html', {"staff_level": user.group.level, "search_flag": "True", "panduan": "True", 'realname': user.real_name, 'position': user.position, 'department': user.company.name, 'apply_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

    def post(self, request):
        user = request.user
        veh_id = request.POST.get('id', None)
        subject = request.POST.get('subject', None)
        route = request.POST.get('route', None)
        travelers_users = request.POST.get('travelers_users', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        is_fix = request.POST.get('is_fix', '否')
        field_leader = request.POST.get('field_leader', None)
        RecordAndPush().OperationRecords(request, "车辆管理")
        if not veh_id:
            if not subject or not route or not start_time or not end_time or not is_fix:
                returnDict = {'code': 500, 'message': '缺少必填参数'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') > datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S'):
                returnDict = {'code': 500, 'message': '预定开始日期大于预定结束日期'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if is_fix == '否' and (datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') < datetime.now()):
                returnDict = {'code': 500, 'message': '非补录单据不能选择今天之前的日期'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            try:
                if travelers_users:
                    travelers_users = re.findall('\((.*?)\)', travelers_users)
                    field_leader_numbers = re.findall('\((.*?)\)', field_leader)
                    start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                    end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                    v = VehicleApply.objects.create(subject=subject, route=route,
                                                    travelers_numbers=', '.join(travelers_users),
                                                    field_leader_numbers=', '.join(field_leader_numbers),
                                                    start_time=start_time, end_time=end_time,
                                                    is_fix=True if is_fix == '是' else False, apply_user=request.user,
                                                    current_audit_user=User.objects.get(real_name=user.company.leaders))
                    temp_list = v.travelers_numbers.split(', ')
                    travelers_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in
                                            temp_list]
                    travelers_users_str = ', '.join(travelers_users_list)
                    v.travelers_names = travelers_users_str
                else:
                    field_leader_numbers = re.findall('\((.*?)\)', field_leader)
                    start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                    end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                    v = VehicleApply.objects.create(subject=subject, route=route, field_leader_numbers=', '.join(field_leader_numbers), start_time=start_time, end_time=end_time,
                                                    is_fix=True if is_fix == '是' else False, apply_user=request.user, current_audit_user=user.company.leaders_id)

                temp_list1 = v.field_leader_numbers.split(', ')
                field_leader_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in temp_list1]
                field_leader_str = ', '.join(field_leader_users_list)
                v.field_leader = field_leader_str
                com = Company.objects.get(abbreviation='CD')
                cd_user_obj = com.head_people
                v.save()
                if user.company.id == 80:
                    company_leader = user.company.head_people
                else:
                    company_leader = user.company.leaders_id
                v.current_audit_user = company_leader
                v.save()
                VehicleAuditRecord.objects.create(notice_id=v, state='unaudit', audit_people=company_leader, audit_note='', node='B')
                VehicleAuditRecord.objects.create(notice_id=v, state='unaudit', audit_people=cd_user_obj, audit_note='', node='YB')
                VehicleAuditRecord.objects.create(notice_id=v, state='unaudit', audit_people=com.leaders_id, audit_note='', node='CGB')
                topic_type = "车辆管理"
                applicant = v.apply_user.real_name
                ApplicationTime = v.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = v.subject[:15] + "……" if len(v.subject) > 15 else v.subject
                try:
                    RecordAndPush().MessagePush(user.company.leaders_id.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': 'success'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            except Exception as e:
                returnDict = {'code': 500, 'message': '创建失败!'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            obj = VehicleApply.objects.get(id=int(veh_id))
            field_leader_numbers = re.findall('\((.*?)\)', field_leader)
            obj.state = 'draft'
            obj.subject = subject
            obj.route = route
            obj.field_leader_numbers = ', '.join(field_leader_numbers),
            obj.start_time = start_time
            obj.end_time = end_time
            field_leader_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in field_leader_numbers]
            field_leader_str = ', '.join(field_leader_users_list)
            obj.field_leader = field_leader_str

            if user.company.id == 80:
                company_leader = user.company.head_people
            else:
                company_leader = user.company.leaders_id
            obj.current_audit_user = company_leader
            obj.save()

            obj.vehicleauditrecord_set.filter(state='unaudit').delete()
            com = Company.objects.get(abbreviation='CD')
            cd_user_obj = com.head_people
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit', audit_people=user.company.leaders_id, audit_note='', node='B')
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit', audit_people=cd_user_obj, audit_note='', node='YB')
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit', audit_people=com.leaders_id, audit_note='', node='CGB')
            topic_type = "车辆管理"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
            try:
                RecordAndPush().MessagePush(user.company.leaders_id.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
            returnDict = {'code': 200, 'message': 'success'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyList(View):
    def get(self, request):
        ready_objs = request.user.vehicle_apply_current_audit_user.all().order_by("-create_time")
        already_objs = request.user.vehicle_apply_already_users.all().order_by("-create_time")
        # ready_list = []
        # already_list = []
        ready_list = [{'apply_user': v_obj.apply_user.real_name, 'subject': v_obj.subject, 'route': v_obj.route,  # 车辆待办
                       'state': v_obj.get_state_display(), 'id': v_obj.id,
                       'audit_user': v_obj.current_audit_user.real_name,
                       'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
                       'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M")} for v_obj in ready_objs]
        already_list = [
            {'apply_user': v_obj.apply_user.real_name, 'subject': v_obj.subject, 'route': v_obj.route,  # 车辆已办
             'state': v_obj.get_state_display(), 'id': v_obj.id,
             'audit_user': v_obj.current_audit_user.real_name if v_obj.current_audit_user else '',
             'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
             'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M")} for v_obj in already_objs]
        returnDict = {'code': 200, 'message': 'success', 'ready_list': ready_list, 'ready_list_count': len(ready_list),
                      'already_list': already_list, 'already_list_count': len(already_list),
                      "staff_level": request.user.level, "search_flag": "True", "panduan": "True", 'flag': True,
                      'realname': request.user.real_name, 'position': request.user.post,
                      'department': request.user.company.name}
        return render(request, 'administrative/vehicle_apply.html', returnDict)


class VehicleApplyDetail(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        vehicles = request.POST.get('vehicles', None)
        drivers = request.POST.get('drivers', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        RecordAndPush().OperationRecords(request, "车辆管理")
        is_cgb = False
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            va_obj = VehicleApply.objects.get(id=int(id))
            topic_type = "车辆管理"
            applicant = va_obj.apply_user.real_name
            ApplicationTime = va_obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = va_obj.subject[:15] + "……" if len(va_obj.subject) > 15 else va_obj.subject
            if va_obj.state == 'draft':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='B', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'fg'
                    com = Company.objects.get(abbreviation='CD')
                    cd_user_obj = com.head_people
                    va_obj.current_audit_user = cd_user_obj
                    try:
                        RecordAndPush().MessagePush(cd_user_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
            elif va_obj.state == 'fg':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='YB', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'ybzr'
                    com = Company.objects.get(id=34)
                    va_obj.current_audit_user = com.leaders_id
                    try:
                        RecordAndPush().MessagePush(com.leaders_id.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                    if vehicles and drivers:
                        va_obj.vehicles = vehicles
                        va_obj.drivers = drivers
                        vehicle_obj = Vehicle.objects.get(registration_number=va_obj.vehicles)
                        VehicleUseInfo.objects.create(vehicle=vehicle_obj, start_time=va_obj.start_time, end_time=va_obj.end_time, driver=va_obj.drivers, apply_id=va_obj)
                    else:
                        returnDict = {'code': 500, 'message': '车队负责人审核需要指定车辆和司机'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    if va_obj.vehicleauditrecord_set.filter(node='B').last().audit_people == va_obj.vehicleauditrecord_set.filter(node='CGB').last().audit_people:
                        is_cgb = True

                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
            elif va_obj.state == 'ybzr':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='CGB', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'cgb'
                    mobiles = []
                    va_obj.current_audit_user = None
                    driver = User.objects.filter(real_name=va_obj.drivers)
                    if driver:
                        mobiles.append(driver.first().mobile)

                    if not va_obj.is_fix and datetime.now() < va_obj.end_time:
                        content = '您的车辆申请已预定成功, 时间：%s-%s, 路线：%s, 同行人员(%s), 车辆(%s), 司机为%s(%s)' % (
                            va_obj.start_time.strftime("%Y-%m-%d %H:%M"), va_obj.end_time.strftime("%Y-%m-%d %H:%M"),
                            va_obj.route, va_obj.field_leader, va_obj.vehicles, va_obj.drivers, User.objects.filter(real_name=va_obj.drivers).first())
                        mobiles.append(va_obj.apply_user.mobile)
                        mobiles = list(set(mobiles))
                        res = send_mssage(mobiles, content)

                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
                    vehicle_use_infos = VehicleUseInfo.objects.filter(apply_id=va_obj)
                    for vehicle_use_info in vehicle_use_infos:
                        vehicle_use_info.delete()

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            va_obj.state = va_obj_state
            va_obj.save()
            vad_obj.update_time = datetime.now()
            vad_obj.state = state
            vad_obj.audit_note = audit_note
            vad_obj.save()
            if is_cgb:
                mobiles = []
                va_obj_state = 'cgb'
                va_obj.state = va_obj_state
                va_obj.current_audit_user = None
                va_obj.save()
                driver = User.objects.filter(real_name=va_obj.drivers)
                if driver:
                    mobiles.append(driver.first().mobile)
                travelers_numbers = va_obj.travelers_numbers.split(', ')
                for travelers_number in travelers_numbers:
                    user_obj = User.objects.filter(job_number=travelers_number)
                    if user_obj:
                        mobiles.append(user_obj.first().mobile)

                field_leader_numbers = va_obj.field_leader_numbers.split(', ')
                for field_leader_number in field_leader_numbers:
                    user_obj = User.objects.filter(job_number=field_leader_number)
                    if user_obj:
                        mobiles.append(user_obj.first().mobile)
                if not va_obj.is_fix and datetime.now() < va_obj.end_time:
                    content = '您的车辆申请已预定成功, 时间：%s-%s, 路线：%s, 同行人员(%s)' % (
                        va_obj.start_time.strftime("%Y-%m-%d %H:%M"), va_obj.end_time.strftime("%Y-%m-%d %H:%M"),
                        va_obj.route, va_obj.field_leader)
                    mobiles.append(va_obj.apply_user.mobile)
                    mobiles = list(set(mobiles))
                    res = send_mssage(mobiles, content)

                b_vad_obj = va_obj.vehicleauditrecord_set.filter(node='B', state='audit').last()
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='CGB', state='unaudit').first()
                vad_obj.update_time = datetime.now()
                vad_obj.state = 'audit'
                vad_obj.audit_note = b_vad_obj.audit_note
                vad_obj.save()

            if request.user not in va_obj.already_users.all():
                va_obj.already_users.add(request.user)
            returnDict = {'code': 200, 'message': '审核成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except Exception as e:
            print("e: ", e)
            returnDict = {'code': 500, 'message': '审批失败请联系管理员'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyWriteView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        subject = request.POST.get('subject', None)
        route = request.POST.get('route', None)
        travelers_users = request.POST.get('travelers_users', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        is_fix = request.POST.get('is_fix', None)

        obj = VehicleApply.objects.get(id=int(id))
        if obj.state not in ('refuse', 'draft'):
            returnData = {'code': 500, 'message': '修改错误，只有为新建和拒绝状态的车辆申请才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        # try:
        if subject:
            obj.subject = subject
        if route:
            obj.route = route
        if start_time:
            start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            obj.start_time = start_time
        if end_time:
            end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
            obj.end_time = end_time
        if is_fix:
            obj.is_fix = True if is_fix == '是' else False
        if travelers_users:
            travelers_users = re.findall('\((.*?)\)', travelers_users)
            obj.travelers_numbers = ', '.join(travelers_users)
            temp_list = obj.travelers_numbers.split(', ')
            travelers_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in
                                    temp_list]
            travelers_users_str = ', '.join(travelers_users_list)
            obj.travelers_names = travelers_users_str

        if len(obj.vehicleauditrecord_set.filter(node='B', state='unaudit')) == 0:
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                              audit_people=user.company.leaders_id,
                                              audit_note='', node='B')
        if len(obj.vehicleauditrecord_set.filter(node='YB', state='unaudit')) == 0:
            com = Company.objects.get(abbreviation='CD')
            cd_user_obj = User.objects.get(real_name=com.director)
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                              audit_people=cd_user_obj, audit_note='',
                                              node='YB')
        if len(obj.vehicleauditrecord_set.filter(node='CGB', state='unaudit')) == 0:
            com = Company.objects.get(abbreviation='CD')
            VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                              audit_people=com.leaders_id, audit_note='',
                                              node='CGB')
        obj.state = 'draft'
        obj.current_audit_user = user.company.leaders_id
        if obj.public_search:
            public_search_obj = obj.public_search
            content = json.loads(public_search_obj.content)
            content['id'] = obj.id
            content['subject'] = obj.subject
            content['route'] = obj.route
            public_search_obj.content = json.dumps(content, ensure_ascii=False)
            public_search_obj.audit_users_already.add(user)
            public_search_obj.current_audit_users.clear()
            public_search_obj.current_audit_users.add(obj.current_audit_user)
            public_search_obj.state = obj.state
            public_search_obj.save()
        obj.save()
        returnDict = {'code': 200, 'message': '修改成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 撤回 终止 作废操作
class VehicleApplyCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = VehicleApply.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'cgb':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的车辆申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.vehicleauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的车辆申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_user = None
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'cgb':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的车辆申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_user = None
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class VehicleApplyBackView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)
        audit_people = request.POST.get('audit_people', None)
        obj = VehicleApply.objects.get(id=int(id))
        audit_people = re.findall('\((.*?)\)', audit_people)
        audit_people_objs = User.objects.filter(job_number__in=audit_people)
        # if state == obj.state:
        #     returnData = {'code': 200, 'message': 'ok！'}
        #     return HttpResponse(json.dumps(returnData), content_type="application/json")
        if obj.state in ('cancel', 'refuse'):
            returnData = {'code': 500, 'message': '已经作废或拒绝的单据，不能退回！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if state == 'draft':
                if audit_people_objs.count() > 0:
                    obj.vehicleauditrecord_set.filter(node='B').delete()
                    for audit_people_obj in audit_people_objs:
                        VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                          audit_people=audit_people_obj,
                                                          audit_note='', node='B')
                obj.current_audit_user = obj.vehicleauditrecord_set.filter(node='B').first().audit_people
                audit_objs = obj.vehicleauditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'fg':
                if obj.state == 'draft':
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                if audit_people_objs.count() > 0:
                    obj.vehicleauditrecord_set.filter(node='YB').delete()
                    for audit_people_obj in audit_people_objs:
                        VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                          audit_people=audit_people_obj,
                                                          audit_note='', node='YB')
                obj.current_audit_user = obj.vehicleauditrecord_set.filter(node='YB').first().audit_people
                audit_objs = obj.vehicleauditrecord_set.filter(node__in=['YB', 'CGB'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'ybzr':
                if obj.state in ['draft', 'fg']:
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                if audit_people_objs.count() > 0:
                    obj.vehicleauditrecord_set.filter(node='CGB').delete()
                    for audit_people_obj in audit_people_objs:
                        VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                          audit_people=audit_people_obj,
                                                          audit_note='', node='CGB')
                obj.current_audit_user = obj.vehicleauditrecord_set.filter(node='CGB').first().audit_people
                audit_objs = obj.vehicleauditrecord_set.filter(node__in=['CGB'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'refuse':
                audit_objs = obj.vehicleauditrecord_set.all()
                obj.current_audit_user = obj.apply_user
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")


class VehicleApplyAdmin(View):
    def get(self, request):
        search_value = request.GET.get("search_value", None)
        if search_value:
            objs = VehicleApply.objects.filter(
                Q(apply_user__real_name__contains=search_value) | Q(subject__contains=search_value)).order_by(
                '-create_time')
        else:
            objs = VehicleApply.objects.all().order_by('-create_time')
        states_dispaly = {'draft': '分管领导',
                          'fg': '车队队长',
                          'ybzr': '车管办领导',
                          'cgb': '结束',
                          'refuse': '拒绝',
                          'cancel': '作废',
                          'stop': '终止',
                          'recall': '撤回',
                          }
        states = ['draft', 'fg', 'ybzr', 'cgb', 'refuse', 'cancel', 'stop', 'recall']

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)
        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   'states': states, 'states_dispaly': states_dispaly, "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'administrative/vehicle_admin.html', context)


class TopicsApplyAdmin(View):
    def get(self, request):
        search_value = request.GET.get("search_value", None)
        if search_value:
            objs = Topics.objects.filter(
                Q(employee__real_name__contains=search_value) | Q(number__contains=search_value) | Q(
                    topics_name__contains=search_value)).order_by('-create_time')
        else:
            objs = Topics.objects.all().order_by('-create_time')
        states_dispaly = {'draft': '分管领导审核',
                          'confirm': '院办/党办主任审核',
                          'audit': '院长/书记审核',
                          'done': '结束',
                          'refuse': '拒绝',
                          'cancel': '作废',
                          'stop': '终止',
                          'recall': '撤回'
                          }
        states = ['draft', 'confirm', 'audit', 'done', 'refuse', 'cancel']

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        # if not search_value:
        #     search_value = ""

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   'states': states, 'states_dispaly': states_dispaly, "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'administrative/topics_admin.html', context)


class ConferenceMemoAdmin(View):
    def get(self, request):
        search_value = request.GET.get("search_value", None)
        if search_value:
            objs = ConferenceMemo.objects.filter(
                Q(apply_user__real_name__contains=search_value) | Q(document_number__contains=search_value) | Q(
                    conference_memo_text__contains=search_value)).order_by('-create_time')
        else:
            objs = ConferenceMemo.objects.all().order_by('-create_time')
        states_dispaly = {'nine': '科室负责人初审',
                          'one': '党办/院办主任',
                          'two': '分管领导',
                          'three': '指定会签人员',
                          'four': '会签',
                          'five': '院长/书记',
                          'six': '拒绝',
                          'seven': '结束',
                          'eight': '分发',
                          'cancel': '作废',
                          'stop': '终止',
                          }
        states = ['nine', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'cancel']

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   'states': states, 'states_dispaly': states_dispaly, "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'administrative/conference_memo_admin.html', context)


class OfficialDocumentsAdmin(View):
    def get(self, request):
        search_value = request.GET.get("search_value", None)
        if search_value:
            objs = OfficialDocuments.objects.filter(
                Q(send_number__contains=search_value) | Q(send_company__contains=search_value) | Q(
                    recive_number__contains=search_value) | Q(title__contains=search_value)).order_by('-create_time')
        else:
            objs = OfficialDocuments.objects.all().order_by('-create_time')
        states_dispaly = {'i': '申请人',
                          'a': '办公室主任审核',
                          'b': '院长/书记审核',
                          'c': '分管领导签批',
                          'd': '科主任传阅',
                          'e': '结束',
                          'f': '拒绝',
                          'g': '待分发',
                          'cancel': '作废',
                          'stop': '终止',
                          'h': '申请人选择分管领导'
                          }
        states = ['i', 'a', 'b', 'c', 'f', 'g', 'h']

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   'states': states, 'states_dispaly': states_dispaly, "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'administrative/official_documents.html', context)


class NoticeAdmin(View):
    def get(self, request):
        search_value = request.GET.get("search_value", None)
        if search_value:
            # objs = Notice.objects.all().order_by('-create_time')
            objs = Notice.objects.filter(
                Q(create_people__real_name__contains=search_value) | Q(name__contains=search_value)).order_by(
                '-create_time')
        else:
            objs = Notice.objects.all().order_by('-create_time')
        states_dispaly = {'draft': '审核中',
                          'audit': '已审核',
                          'unaudit': '拒绝'

                          }
        states = ['draft', 'audit', 'unaudit']

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   'states': states, 'states_dispaly': states_dispaly, "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        return render(request, 'system_setup/Notice_Managerment.html', context)


class CompanyAdmin(View):
    def post(self, request):
        id = request.POST.get("id", None)
        leaders = request.POST.get("fgld", None)
        ks_name = request.POST.get("ks_name", None)
        ksjc = request.POST.get("ksjc", None)
        head_nurse = request.POST.get("hsz", None)
        director = request.POST.get("zhuren", None)
        deputy_director = request.POST.get("fuzhuren", None)
        head_people = request.POST.get("head_people", None)
        obj = Company.objects.get(id=int(id))

        # 修改科室名称
        obj.name = ks_name

        # 修改科室简称
        obj.abbreviation = ksjc

        # 修改分管领导
        obj.leaders_id = User.objects.get(id=int(leaders))

        # 修改负责人
        head_people_list = re.findall('\((.*?)\)', head_people)
        if len(head_people_list):
            head_people_obj = User.objects.get(job_number=head_people_list[0])
            obj.head_people = head_people_obj

        # 修改科主任
        if director:
            director_list = re.findall('\((.*?)\)', director)
            if len(director_list):
                director_obj = User.objects.get(job_number=director_list[0])
                if director_obj != obj.director_id:
                    user_group = 6
                    director_or_not_obj = Company.objects.filter(~Q(id=obj.id), director_id=obj.director_id)
                    if director_or_not_obj.count():
                        if director_or_not_obj.first().is_functional:
                            user_group = 3
                        else:
                            user_group = 4
                    else:
                        deputy_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=obj.director_id).count()
                        if deputy_or_not_obj:
                            user_group = 7
                        else:
                            HeadNurseObj = Company.objects.filter(~Q(id=obj.id), head_nurse_id=obj.director_id).count()
                            if HeadNurseObj:
                                user_group = 5

                    if obj.director_id:
                        obj.director_id.group_id = user_group
                        obj.director_id.save()

                    obj.director_id = director_obj
                    if obj.is_functional:
                        director_obj.group_id = 3
                    else:
                        director_obj.group_id = 4
                    director_obj.company = obj
                    director_obj.save()
        else:
            director_or_not_obj = Company.objects.filter(~Q(id=obj.id), director_id=obj.director_id)
            user_group = 6
            if director_or_not_obj.count():
                if director_or_not_obj.first().is_functional:
                    user_group = 3
                else:
                    user_group = 4
            else:
                deputy_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=obj.director_id).count()
                if deputy_or_not_obj:
                    user_group = 7
                else:
                    HeadNurseObj = Company.objects.filter(~Q(id=obj.id), head_nurse_id=obj.director_id).count()
                    if HeadNurseObj:
                        user_group = 5

            if obj.director_id:
                obj.director_id.group_id = user_group
                obj.director_id.save()

            obj.director_id = None
            obj.save()


        # 修改护士长
        if head_nurse:
            head_nurse_list = re.findall('\((.*?)\)', head_nurse)
            if len(head_nurse_list):
                head_nurse_obj = User.objects.get(job_number=head_nurse_list[0])
                if head_nurse_obj != obj.head_nurse_id:
                    user_group = 6
                    director_or_not_obj = Company.objects.filter(~Q(id=obj.id), director_id=obj.head_nurse_id)
                    if director_or_not_obj.count():
                        if director_or_not_obj.first().is_functional:
                            user_group = 3
                        else:
                            user_group = 4
                    else:
                        deputy_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=obj.head_nurse_id).count()
                        if deputy_or_not_obj:
                            user_group = 7
                        else:
                            HeadNurseObj = Company.objects.filter(~Q(id=obj.id), head_nurse_id=obj.head_nurse_id).count()
                            if HeadNurseObj:
                                user_group = 5

                    if obj.head_nurse_id:
                        obj.head_nurse_id.group_id = user_group
                        obj.head_nurse_id.save()
                    obj.head_nurse_id = head_nurse_obj
                    head_nurse_obj.group_id = 5
                    head_nurse_obj.save()
        else:
            user_group = 6
            director_or_not_obj = Company.objects.filter(~Q(id=obj.id), director_id=obj.head_nurse_id)
            if director_or_not_obj.count():
                if director_or_not_obj.first().is_functional:
                    user_group = 3
                else:
                    user_group = 4
            else:
                deputy_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=obj.head_nurse_id).count()
                if deputy_or_not_obj:
                    user_group = 7
                else:
                    HeadNurseObj = Company.objects.filter(~Q(id=obj.id), head_nurse_id=obj.head_nurse_id).count()
                    if HeadNurseObj:
                        user_group = 5

            if obj.head_nurse_id:
                obj.head_nurse_id.group_id = user_group
                obj.head_nurse_id.save()
            obj.head_nurse_id = None
            obj.save()

        # 修改副主任
        if deputy_director:
            deputy_director_list = re.findall('\((.*?)\)', deputy_director)
            if len(deputy_director_list):
                old_deputy_director_obj = obj.deputy_director_ids.all()
                for uu in old_deputy_director_obj:
                    deputy_director_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=uu).count()
                    head_or_not_obj = Company.objects.filter(director_id=uu).count()            # 是否是主任
                    head_nurse_not_obj = Company.objects.filter(head_nurse_id=uu).count()            # 是否是护士长
                    if head_or_not_obj:
                        if uu.company.is_functional:
                            user_group = 3
                        else:
                            user_group = 4
                    elif deputy_director_or_not_obj:
                        user_group = 7
                    elif head_nurse_not_obj:
                        user_group = 5
                    else:
                        user_group = 6
                    uu.group_id = user_group
                    uu.save()

                obj.deputy_director_ids.clear()
                for kk in deputy_director_list:
                    user_obj = User.objects.get(job_number=kk.strip())
                    obj.deputy_director_ids.add(user_obj)
                    user_group = 7
                    user_head_not_obj = Company.objects.filter(director_id=user_obj)              # 是否是主任

                    if user_head_not_obj:
                        user_obj.company = user_head_not_obj.first()
                        if user_head_not_obj.first().is_functional:
                            user_group = 3
                        else:
                            user_group = 4
                    user_obj.group_id = user_group
                    user_obj.save()
        else:
            old_deputy_director_obj = obj.deputy_director_ids.all()
            for uu in old_deputy_director_obj:
                deputy_director_or_not_obj = Company.objects.filter(~Q(id=obj.id), deputy_director_ids=uu).count()
                head_or_not_obj = Company.objects.filter(director_id=uu).count()  # 是否是主任
                head_nurse_not_obj = Company.objects.filter(head_nurse_id=uu).count()  # 是否是护士长
                if head_or_not_obj:
                    if uu.company.is_functional:
                        user_group = 3
                    else:
                        user_group = 4
                elif deputy_director_or_not_obj:
                    user_group = 7
                elif head_nurse_not_obj:
                    user_group = 5
                else:
                    user_group = 6
                uu.group_id = user_group
                uu.save()

            obj.deputy_director_ids.clear()

        obj.save()
        returnDict = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class CompanyDetailAdmin(View):
    def get(self, request):
        id = request.GET.get("id", None)
        obj = Company.objects.get(id=int(id))
        context = {'obj': obj, 'realname': request.user.real_name, 'position': request.user.post}
        return render(request, 'system_setup/company_detail_admin.html', context)


class meet_statistics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        meet_all_list, dep_all_dict = select_mysql().select_data()
        all_query_set = ConferenceRoomApplication.objects.all().order_by("-statr_time")
        all_data_list = []
        for tt in all_query_set:
            one_dict = {}
            one_dict["name"] = tt.names
            one_dict["department"] = tt.department
            one_dict["particular"] = tt.particulars
            one_dict["start_time"] = str(tt.statr_time)[:-3]
            one_dict["end_time"] = str(tt.end_time)[:-3]
            one_dict["status"] = tt.status
            all_data_list.append(one_dict)

        return render(request, "personal_center/meet_statistics.html",
                      {'realname': real_name, 'position': position, 'department': department,
                       "meet_all_list": meet_all_list, "dep_all_dict": dep_all_dict, "all_data_list": all_data_list})


class Vehicle_apply_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        already = request.GET.get("type", None)
        car_id = request.GET.get("id", None)
        already_type = ""
        if already:
            already_type = True
        v_obj = VehicleApply.objects.get(id=int(car_id))
        audit_dic = {}
        for audit_obj in v_obj.vehicleauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        vehicle_use_infos = VehicleUseInfo.objects.filter(Q(start_time__range=[v_obj.start_time, v_obj.end_time]) | Q(end_time__range=[v_obj.start_time, v_obj.end_time]))
        used_vehicle_list = [vehicle_use_info.vehicle for vehicle_use_info in vehicle_use_infos]
        vehicle_objs = Vehicle.objects.filter(available='1')
        vehicle_list = [vehicle_obj for vehicle_obj in vehicle_objs if vehicle_obj not in used_vehicle_list]
        vehicle_list = [{'number': temp.registration_number} for temp in vehicle_list]

        used_driver_list = [vehicle_use_info.driver for vehicle_use_info in vehicle_use_infos]
        driver_objs = Driver.objects.all()
        driver_list = [{'name': temp.name} for temp in driver_objs if temp.name not in used_driver_list]
        is_stop = 'true' if v_obj.state in ['draft', 'fg', 'ybzr', 'refuse'] and request.user == v_obj.apply_user else 'false'
        is_audit = 'true' if v_obj.state != 'refuse' and v_obj.current_audit_user == request.user else 'false'
        is_edit = 'true' if (v_obj.state == 'refuse' and v_obj.apply_user == request.user) else 'false'
        context = {'realname': real_name, 'position': position, 'department': department, "already_type": already_type, 'v_obj': v_obj, 'audit_dic': audit_dic,
                   "is_stop": is_stop, "is_audit": is_audit, "vehicle_list": vehicle_list, "driver_list": driver_list, "is_edit": is_edit}
        return render(request, "personal_center/Vehicle_apply_detail.html", context)


def get_department(department):
    try:
        dep_obj = Department.objects.get(name=department)
        if dep_obj.parent_id > 9:
            print('下级科室')
            department = Department.objects.get(id=dep_obj.parent_id).name
            return get_department(department)
        else:
            return department
    except Exception as e:
        print('获取下级科室失败！', e)
        return department


def get_acronym(str_data):
    """
    获取字符串的首字母
    :param str_data: 字符串
    :return: 字符串
    """
    return "".join([i[0][0] for i in pinyin(str_data)]).upper()


class TopicsListView(View):
    def get(self, request):
        context = {'realname': request.user.real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "administrative_topics"}
        # 改为议题我的申请页面
        return render(request, 'personal_center/add_topic_create_page_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        topic_type = request.POST.get("topic_type", '')  # 查询类型
        if topic_type:
            objs = user.topics_set.filter(Q(topics_name__contains=search_data) |
                                          Q(number__contains=search_data), type=topic_type).order_by('-create_time')
        else:
            objs = user.topics_set.filter(Q(topics_name__contains=search_data) |
                                          Q(number__contains=search_data)).order_by('-create_time')
        data_list = []
        for obj in objs:
            examine_obj = obj.topicsauditrecord_set.filter(state__in=['audit', 'draft']).count()
            if obj.state == 'draft' and not examine_obj:
                url = f'<a href="SubjectDetailst.html?views=1&id={str(obj.id)}" id="{str(obj.id)}">查看</a> | <a href="Issue_modify.html?id={str(obj.id)}">修改</a>'
            else:
                url = f"<a href='/administrative/topics_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'cg' else (f'<a href="SubjectDetailst.html?views=1&id={str(obj.id)}">查看</a>' if obj.state != "stop" else f'<a href="SubjectDetailst.html?views=1&id={str(obj.id)}">查看</a> | <a href="javascript:;" id={obj.id} onclick="del_draft(this.id)" style="color:red;">删除</a>')
                # url = f'<a href="{url_href}">查看</a>'
            data_list.append({'id': obj.id, 'number': obj.number, 'topics_name': obj.topics_name,
                      'current_audit_user': obj.current_audit_user, 'state_dispaly': obj.get_state_str(),
                      'state': obj.state, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                      'url': url})

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class add_topic(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        top_id = request.GET.get("id", None)
        objs = ''
        if top_id:
            objs = Topics.objects.get(id=int(top_id))

        received_obj, company_type = '', ''
        received_audit_dic = {}
        received_id = request.GET.get("received_id", '')
        if received_id:
            received_obj = OfficialDocuments.objects.get(id=int(received_id))
            company_type = "yb" if received_obj.apply_user.company.id == 80 else "db"
            for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                if audit_obj.node in received_audit_dic:
                    received_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                      'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    received_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str( audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        abbreviation = request.user.company.abbreviation
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)

        now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]
        db_obj = Sequence.objects.filter(type="JYDB-" + abbreviation, topic_year=now_year)
        if db_obj:
            db_obj = db_obj.first()
            db_num = str(db_obj.next_sequence).zfill(2)
        else:
            db_num = '01'

        yb_obj = Sequence.objects.filter(type="JYYB-" + abbreviation, topic_year=now_year)
        if yb_obj:
            yb_obj = yb_obj.first()
            yb_num = str(yb_obj.next_sequence).zfill(2)
        else:
            yb_num = '01'

        xz_obj = Sequence.objects.filter(type="JYXZLH-" + abbreviation, topic_year=now_year)
        if xz_obj:
            xz_obj = xz_obj.first()
            xz_num = str(xz_obj.next_sequence).zfill(2)
        else:
            xz_num = '01'
        db_Serial_number = "JYDB-" + abbreviation + "-" + now_year + "-" + db_num
        yb_Serial_number = "JYYB-" + abbreviation + "-" + now_year + "-" + yb_num
        lh_Serial_number = "JYXZLH-" + abbreviation + "-" + now_year + "-" + xz_num

        db_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", '/')} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=db_Serial_number, file_type="0")]
        yb_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", '/')} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=yb_Serial_number, file_type="0")]
        lh_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", '/')} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=lh_Serial_number, file_type="0")]
        leaders = User.objects.filter(group_id=2, is_delete=False)
        return render(request, "personal_center/add_topic.html",
                      {'realname': real_name, 'position': position, 'department': department, "received_obj": received_obj if received_obj else '', "company_type": company_type,
                       "company_list": company_list, "db_Serial_number": db_Serial_number, "CompanyId": request.user.company.id, "received_audit_dic": received_audit_dic,
                       "yb_Serial_number": yb_Serial_number, "lh_Serial_number": lh_Serial_number, "zbb_flag": "true" if request.user.company.id == 9 else "false",
                       "db_file_list": db_file_list, "yb_file_list": yb_file_list, "lh_file_list": lh_file_list, "received_id": received_obj.id if received_obj else '',
                       "uuid": uuid.uuid1(), "leaders": leaders, "objs": objs})


# 议题审批详情
class SubjectDetailst(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        view_s = request.GET.get("views", None)
        ids = request.GET.get("id", None)
        flag = ""
        if view_s:
            flag = True
        revocation_flag = 'true'  # 撤回标签，’true‘ 有该权限

        try:
            topics_obj = Topics.objects.get(id=int(ids))
        except Exception as e:
            returnDict = {'code': 500, 'message': '获取详情失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic = {}
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            data_dic = {'apply_user': topics_obj.employee.real_name,
                        'department': topics_obj.employee.department,
                        'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list,
                        'number': topics_obj.number,
                        'topics_name': topics_obj.topics_name,
                        'topics_text': base64.b64decode(topics_obj.topics_text).decode(),
                        'topics_basis': base64.b64decode(topics_obj.topics_basis).decode(),
                        'solution': base64.b64decode(topics_obj.solution).decode() if topics_obj.solution != "空" else "",
                        'db_topics_text': base64.b64decode(topics_obj.db_topics_text).decode() if topics_obj.db_topics_text else "",
                        'db_topics_basis': base64.b64decode(topics_obj.db_topics_basis).decode() if topics_obj.db_topics_basis else "",
                        'db_solution': base64.b64decode(topics_obj.db_solution).decode() if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate,
                        'help_department': help_department,
                        'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "",
                        'ysje': topics_obj.ysje if topics_obj.ysje else "",
                        'uuid': topics_obj.uuid,
                        'audit_list': audit_dic,
                        'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                        'is_stop': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "refuse", "OPR"] and request.user == topics_obj.employee else 'false',
                        'is_audit': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "PG", "db_one_step", "db_two_step", "db_three_step", "OPR"] and topics_obj.current_audit_user == request.user.real_name else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
        try:
            if topics_obj.type == 'db' and topics_obj.HouseToParty_id:
                yb_obj = Topics.objects.get(id=topics_obj.HouseToParty_id)
                db_obj = topics_obj
                db_meeting_obj = topic_meeting.objects.get(topic=db_obj) if db_obj and db_obj.state == 'done' else ''
                db_vote_obj = VoteLeader.objects.filter(topics_id=db_meeting_obj).first() if db_obj.state == 'done' else ''
            else:
                yb_obj = topics_obj
                db_vote_obj = ""
            meeting_obj = topic_meeting.objects.get(topic=yb_obj) if yb_obj.state == 'done' else ''
            yb_vote_obj = VoteLeader.objects.filter(topics_id=meeting_obj).first() if yb_obj.state == 'done' else ''

        except Exception as E:
            yb_vote_obj = ""
            db_vote_obj = ""

        received_audit_dic, company_type = {}, ''
        received_file_list = []
        if topics_obj.received_foreign:
            received_obj = topics_obj.received_foreign
            company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
            for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                if audit_obj.node in received_audit_dic:
                    received_audit_dic[audit_obj.node].append(
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    received_audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            received_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.received_foreign.uuid)]


        return render(request, "personal_center/SubjectDetailst.html", {'realname': real_name, 'position': position, 'department': department, "flag": flag, 'revocation_flag': revocation_flag, "id": ids,
        "data_dic": data_dic, "obj": topics_obj, 'vote_obj': yb_vote_obj, "db_vote_obj": db_vote_obj, 'received_audit_dic': received_audit_dic, 'company_type': company_type, "received_file_list": received_file_list})

    def post(self, request):
        id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = Topics.objects.filter(id=id)
        st = obj.update(state=state)
        if st:
            returnDict = {'code': 200, 'success': '撤回成功！'}
        else:
            returnDict = {'code': 400, 'success': '撤回失败！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class topic_directory(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]

        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict = [], [], [], {}, {}, {}
        Yb_AllList = []
        YbList = Topics.objects.filter(type='yb', is_meeting='a', state='unmetting')
        yb_unsorted_list = []
        for i in range(len(YbList)):
            yb_dict = {'id': YbList[i].id, "name": YbList[i].topics_name, "number": YbList[i].number,
                       "dep": YbList[i].employee.company.name, "topic_type": "付款类" if YbList[i].topic_type == "1" else "经济合同类" if YbList[i].topic_type == "2" else "项目类" if YbList[i].topic_type == "3" else "文件类" if YbList[i].topic_type == "4" else "方案类" if YbList[i].topic_type == "5" else "其他事项" if YbList[i].topic_type == "6" else "",
                       'tjr': YbList[i].employee.real_name, 'tjsj': str(YbList[i].create_time).split(".")[0][:-3],
                       'shsj': YbList[i].topicsauditrecord_set.filter(node='YZ/SJ').order_by('update_time').last().update_time,
                       'hbr': YbList[i].topicsauditrecord_set.filter(node='B').last().audit_people.real_name if YbList[i].topicsauditrecord_set.filter(node='B') else YbList[i].topicsauditrecord_set.filter(node='YB/DB').last().audit_people.real_name}
            yb_unsorted_list.append(yb_dict)

        yb_unsorted_list.sort(key=itemgetter('shsj'), reverse=False)

        for ij in yb_unsorted_list:
            if ij["dep"] in YbDict:
                YbDict[ij["dep"]].append(ij)
            else:
                YbDict[ij["dep"]] = [ij]

        for iJ in YbDict:
            Yb_AllList += YbDict[iJ]

        for ij in range(len(Yb_AllList)):
            Yb_AllList[ij]["serial_number"] = ij + 1
            Yb_AllList[ij]['shsj'] = str(Yb_AllList[ij]["shsj"]).split(".")[0][:-3]
            YbAllList.append(Yb_AllList[ij])

        DbList = Topics.objects.filter(type='db', is_meeting='a', state='unmetting').order_by("update_time")
        YbZhuanDbAllList, YbZhuanDbAllDict, YbDbAllDict, Db_AllList, Db_zh_alllidt, Db_all_list = [], {}, {}, [], [], []
        db_unsorted_list = []
        for t in range(len(DbList)):
            db_dict = {'id': DbList[t].id, "name": DbList[t].topics_name, "number": DbList[t].number,
                       "dep": DbList[t].employee.company.name, 'tjr': DbList[t].employee.real_name,
                       'tjsj': str(DbList[t].create_time).split(".")[0][:-3],
                       'shsj': DbList[t].topicsauditrecord_set.filter(node__in=['YZ/SJ', 'sj']).order_by('update_time').last().update_time,
                       'hbr': DbList[t].topicsauditrecord_set.filter(node='B').last().audit_people.real_name if DbList[t].topicsauditrecord_set.filter(node='B') else DbList[t].topicsauditrecord_set.filter(node='YB/DB').last().audit_people.real_name, 'is_yb': True if DbList[t].is_yb else False}
            db_unsorted_list.append(db_dict)

        db_unsorted_list.sort(key=itemgetter('shsj'), reverse=False)
        for kl in db_unsorted_list:
            if kl['dep'] in YbDbAllDict:
                YbDbAllDict[kl['dep']].append(kl)
            else:
                YbDbAllDict[kl['dep']] = [kl]

        for JJ in YbDbAllDict:
            Db_all_list += YbDbAllDict[JJ]
        for TJ in range(len(Db_all_list)):
            Db_all_list[TJ]["serial_number"] = TJ + 1
            Db_all_list[TJ]['shsj'] = str(Db_all_list[TJ]['shsj']).split(".")[0][:-3]
            DbAllList.append(Db_all_list[TJ])

        LhList = Topics.objects.filter(type='xz', is_meeting='a', state='unmetting').order_by("update_time")
        xz_unsorted_list = []
        for iy in range(len(LhList)):
            lh_dict = {'id': LhList[iy].id, "name": LhList[iy].topics_name, "number": LhList[iy].number,
                       "dep": LhList[iy].employee.company.name, 'tjr': LhList[iy].employee.real_name,
                       'tjsj': str(LhList[iy].create_time).split(".")[0][:-3],
                       'shsj': LhList[iy].topicsauditrecord_set.filter(node__in=['YB/DB', 'YZ/SJ']).order_by('update_time').last().update_time,
                       'hbr': LhList[iy].topicsauditrecord_set.filter(node='B').last().audit_people.real_name if LhList[iy].topicsauditrecord_set.filter(node='B') else LhList[iy].topicsauditrecord_set.filter(node='YB/DB').last().audit_people.real_name}
            xz_unsorted_list.append(lh_dict)

        xz_unsorted_list.sort(key=itemgetter('shsj'), reverse=False)
        for gh in xz_unsorted_list:
            if gh["dep"] in LhDict:
                LhDict[gh["dep"]].append(gh)
            else:
                LhDict[gh["dep"]] = [gh]

        Lh_AllList = []
        for IY in LhDict:
            Lh_AllList += LhDict[IY]

        for Yi in range(len(Lh_AllList)):
            Lh_AllList[Yi]["serial_number"] = Yi + 1
            Lh_AllList[Yi]['shsj'] = str(Lh_AllList[Yi]['shsj']).split(".")[0][:-3]
            XzAllList.append(Lh_AllList[Yi])

        # *********************************************** 党办会议次数 ***********************************************
        Db_meet_num_list = Topics.objects.filter(type='db', iss_year=now_year).values("meetings_num")
        Db_meet_num = max([int(i["meetings_num"]) for i in Db_meet_num_list]) + 1 if Db_meet_num_list else 1
        # *********************************************** 院办会议次数 ***********************************************
        Yb_meet_num_list = Topics.objects.filter(type='yb', iss_year=now_year).values("meetings_num")
        Yb_meet_num = max([int(i["meetings_num"]) for i in Yb_meet_num_list]) + 1 if Yb_meet_num_list else 1
        # *********************************************** 院办会议次数 ***********************************************
        Xz_meet_num_list = Topics.objects.filter(type='xz', iss_year=now_year).values("meetings_num")
        Xz_meet_num = max([int(i["meetings_num"]) for i in Xz_meet_num_list]) + 1 if Xz_meet_num_list else 1

        button_flag = True

        leader_obj = User.objects.filter(group__in=[1, 2])

        LeaderList = User.objects.filter(group=2)
        dzb_obj = Company.objects.get(id=3).head_people
        if request.user in LeaderList and request.user != dzb_obj:
            button_flag = False

        yb_flag = 'true' if request.user.company.id == 80 else 'false'
        return render(request, "personal_center/topic_directory.html",
                      {'realname': real_name, 'position': position, 'department': department, "DbAllList": DbAllList,
                       "YbAllList": YbAllList, "XzAllList": XzAllList, "Db_meet_num": Db_meet_num, "yb_flag": yb_flag,
                       "Yb_meet_num": Yb_meet_num, "Xz_meet_num": Xz_meet_num, "now_year": now_year,
                       "YbZhuanDbAllList": YbZhuanDbAllList, "leader_obj": leader_obj, "button_flag": button_flag})


class Confirmation(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)
        file_name = request.POST.get("file_name", None)
        iss_type = request.POST.get("iss_type", None)
        meeting_adress = request.POST.get("meeting_adress", None)
        meeting_time = request.POST.get("meeting_time", None)
        notification = request.POST.get("notification", None)
        RecordAndPush().OperationRecords(request, "行政例会上会")
        pass_yb_list = []
        no_pass_yb = []
        if iss_type == "db":
            for ii in json.loads(id_list):
                yiti_yb_obj = Topics.objects.get(id=int(ii))
                if yiti_yb_obj.is_yb:
                    pass_yb_list.append(ii)
                else:
                    no_pass_yb.append(ii)
            id_list = json.dumps(pass_yb_list + no_pass_yb)
        # *********************************** 生成pdf文件 ****************************************
        pdf_file_list = []
        page_list = []
        if iss_type != "db":
            for i in json.loads(id_list):
                one_dict = {}
                yiti_yb_obj = Topics.objects.get(id=int(i))
                one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
                one_dict["title"] = yiti_yb_obj.topics_name
                one_dict["dep"] = yiti_yb_obj.employee.department
                one_dict["tjr"] = yiti_yb_obj.employee.real_name
                one_dict["ytbh"] = yiti_yb_obj.number
                one_dict["ygys"] = yiti_yb_obj.topics_estimate
                one_dict["nrwb"] = yiti_yb_obj.nrwb
                one_dict["zcyj"] = yiti_yb_obj.zcwb
                one_dict["fawb"] = yiti_yb_obj.fawb
                one_dict["ysje"] = yiti_yb_obj.ysje
                one_dict["jfly"] = yiti_yb_obj.jfly
                one_dict["nrwb_base"] = yiti_yb_obj.topics_text
                one_dict["fawb_base"] = yiti_yb_obj.solution
                one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
                audit_dic = {}
                for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.get_state_display(),
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': os.getcwd() + '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': os.getcwd() + '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

                one_dict["audit_dic"] = audit_dic
                if iss_type == "yb":
                    file_path = directory().yb_func(one_dict, iss_type, file_name)
                else:
                    file_path = directory().xz_func(one_dict, iss_type, file_name)

                pdf_file_list.append(file_path)
                text_page = get_num_pages(file_path)
                pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_yb_obj.uuid, file_type="0")
                for path in pdf_path_list:
                    pdf_file_path = os.getcwd() + path.pdf_path
                    if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                        if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                            pdf_file_list.append(pdf_file_path)
                            enclosure_page = get_num_pages(pdf_file_path)
                            text_page += enclosure_page
                        elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                            pdf_tp_path = image_to_pdf(pdf_file_path)
                            pdf_file_list.append(pdf_tp_path)
                            enclosure_page = get_num_pages(pdf_tp_path)
                            text_page += enclosure_page

                page_list.append(text_page)

        file_merger = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        for pdf in pdf_file_list:
            file_merger.append(pdf)  # 合并pdf文件
        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file"
        if not os.path.exists(Issue_information_path):
            os.makedirs(Issue_information_path)
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料_numbered.pdf"  # PDF 议题资料路径
        file_merger.write(pdf_path)
        if os.path.exists(f"{Issue_information_path}/{file_name}-会议资料.pdf"):
            os.remove(f"{Issue_information_path}/{file_name}-会议资料.pdf")
        os.rename(pdf_path, f"{Issue_information_path}/{file_name}-会议资料.pdf")

        # add_page_numgers(pdf_path)
        mobiles, all_db_data_list = [], []
        # *********************************** 生成excel文件 ****************************************
        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict, IdList = [], [], [], {}, {}, {}, []
        if iss_type == 'yb':
            Yb_AllList = []
            for i in range(len(json.loads(id_list))):
                Ybobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                yb_list = [Ybobj.topics_name, Ybobj.employee.department, Ybobj.employee.real_name,
                           str(Ybobj.create_time).split(".")[0][:-3],
                           str(Ybobj.topicsauditrecord_set.all().order_by('update_time').last().update_time).split(".")[0][:-3],
                           Ybobj.employee.company.leaders, Ybobj.id]

                if Ybobj.employee.department in YbDict:
                    YbDict[Ybobj.employee.department].append(yb_list)
                else:
                    YbDict[Ybobj.employee.department] = [yb_list]

            for iJ in YbDict:
                Yb_AllList += YbDict[iJ]

            for ij in range(len(Yb_AllList)):
                Yb_AllList[ij].insert(0, ij + 1)
                start_page = sum(page_list[:ij])+1
                end_page = sum(page_list[:ij+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Yb_AllList[ij].append(page_number)
                YbAllList.append(Yb_AllList[ij])

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/yb"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            if int(notification):
                create_table().send_msg(YbAllList, file_name, meeting_time, meeting_adress)
            create_table().yb_excel(YbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
            for ids in YbAllList:
                IdList.append(ids[-2])

        elif iss_type == 'db':
            YbZhuanDbAllList, YbZhuanDbAllDict, YbDbAllDict, Db_AllList, Db_zh_alllidt, Db_all_list, Yb_ZhuanDbAllList = [], {}, {}, [], [], [], []
            for i in range(len(json.loads(id_list))):
                Dbobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                db_dict = [Dbobj.topics_name, Dbobj.employee.department, Dbobj.employee.real_name,
                           str(Dbobj.create_time).split(".")[0][:-3], str(Dbobj.update_time).split(".")[0][:-3],
                           Dbobj.employee.company.director if Dbobj.employee.company.director else Dbobj.employee.company.deputy_director, Dbobj.id]
                if Dbobj.is_yb:
                    if Dbobj.employee.department in YbZhuanDbAllDict:
                        YbZhuanDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbZhuanDbAllDict[Dbobj.employee.department] = [db_dict]

                else:
                    if Dbobj.employee.department in YbDbAllDict:
                        YbDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbDbAllDict[Dbobj.employee.department] = [db_dict]

            for Tj in YbZhuanDbAllDict:
                Db_zh_alllidt += YbZhuanDbAllDict[Tj]
            for TT in range(len(Db_zh_alllidt)):
                Db_zh_alllidt[TT].insert(0, TT + 1)
                new_list = Db_zh_alllidt[TT][:2]
                new_list.append(Db_zh_alllidt[TT][-1])
                YbZhuanDbAllList.append(new_list)

            for JJ in YbDbAllDict:
                Db_all_list += YbDbAllDict[JJ]
            for TJ in range(len(Db_all_list)):
                Db_all_list[TJ].insert(0, TJ + 1)
                Db_AllList.append(Db_all_list[TJ])

            all_db_data_list = YbZhuanDbAllList + Db_AllList
            for i in all_db_data_list:
                one_dict = {}
                yiti_yb_obj = Topics.objects.get(id=int(i[-1]))
                one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
                one_dict["title"] = yiti_yb_obj.topics_name
                one_dict["dep"] = yiti_yb_obj.employee.department
                one_dict["tjr"] = yiti_yb_obj.employee.real_name
                one_dict["ytbh"] = yiti_yb_obj.number
                one_dict["ygys"] = yiti_yb_obj.topics_estimate
                one_dict["nrwb"] = yiti_yb_obj.nrwb
                one_dict["zcyj"] = yiti_yb_obj.zcwb
                one_dict["fawb"] = yiti_yb_obj.fawb
                one_dict["ysje"] = yiti_yb_obj.ysje
                one_dict["jfly"] = yiti_yb_obj.jfly
                one_dict["nrwb_base"] = yiti_yb_obj.topics_text
                one_dict["fawb_base"] = yiti_yb_obj.solution
                one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
                audit_dic = {}
                for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.get_state_display(),
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': os.getcwd() + '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': os.getcwd() + '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

                one_dict["audit_dic"] = audit_dic
                file_path = directory().db_func(one_dict, iss_type, file_name)

                pdf_file_list.append(file_path)
                text_page = get_num_pages(file_path)
                pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_yb_obj.uuid, file_type="0")
                for path in pdf_path_list:
                    pdf_file_path = os.getcwd() + path.pdf_path
                    if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                        if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                            pdf_file_list.append(pdf_file_path)
                            enclosure_page = get_num_pages(pdf_file_path)
                            text_page += enclosure_page
                        elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                            pdf_tp_path = image_to_pdf(pdf_file_path)
                            pdf_file_list.append(pdf_tp_path)
                            enclosure_page = get_num_pages(pdf_tp_path)
                            text_page += enclosure_page

                page_list.append(text_page)

            for ij in range(len(YbZhuanDbAllList)):
                start_page = sum(page_list[:ij])+1
                end_page = sum(page_list[:ij+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                YbZhuanDbAllList[ij].append(page_number)
                Yb_ZhuanDbAllList.append(YbZhuanDbAllList[ij])

            page_start = len(YbZhuanDbAllList)
            for ij in range(len(Db_AllList)):
                start_page = sum(page_list[:page_start])+1
                end_page = sum(page_list[:page_start+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Db_AllList[ij].append(page_number)
                DbAllList.append(Db_AllList[ij])
                page_start += 1
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/db"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            if int(notification):
                create_table().send_msg(DbAllList, file_name, meeting_time, meeting_adress, ty="db")
            create_table().db_excel(Yb_ZhuanDbAllList, DbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
            for ids in Yb_ZhuanDbAllList:
                IdList.append(ids[-2])
            for ids in DbAllList:
                IdList.append(ids[-2])

        else:
            Xz_AllList = []
            for i in range(len(json.loads(id_list))):
                Xzobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                # mobiles.append(Xzobj.employee.mobile)
                lh_dict = [Xzobj.topics_name, Xzobj.employee.department, Xzobj.employee.real_name,
                           str(Xzobj.create_time).split(".")[0][:-3],
                           str(Xzobj.update_time).split(".")[0][:-3], Xzobj.employee.company.leaders, Xzobj.id]
                if Xzobj.employee.department in LhDict:
                    LhDict[Xzobj.employee.department].append(lh_dict)
                else:
                    LhDict[Xzobj.employee.department] = [lh_dict]
            Lh_AllList = []
            for IY in LhDict:
                Lh_AllList += LhDict[IY]

            for Yi in range(len(Lh_AllList)):
                Lh_AllList[Yi].insert(0, Yi + 1)
                XzAllList.append(Lh_AllList[Yi])

            for IJ in range(len(XzAllList)):
                start_page = sum(page_list[:IJ])+1
                end_page = sum(page_list[:IJ+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                XzAllList[IJ].append(page_number)
                Xz_AllList.append(XzAllList[IJ])

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/xz"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            if int(notification):
                create_table().send_msg(Xz_AllList, file_name, meeting_time, meeting_adress)
            create_table().yb_excel(Xz_AllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
            for ids in Xz_AllList:
                IdList.append(ids[-2])

        now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]
        meet_num_list = Topics.objects.filter(type=f'{iss_type}', iss_year=now_year).values("meetings_num")
        meet_num = int(max([int(i["meetings_num"]) for i in meet_num_list])) + 1 if meet_num_list else 1

        real_name_list, job_num_list, message_content = [], [], f'<p>尊敬的院领导：</p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 您好！<span style="color: rgb(255, 0, 0);">{file_name}&nbsp;</span>将于&nbsp;<span style="color: rgb(255, 0, 0);">{str(meeting_time).split(".")[0][:-3]}</span>&nbsp;在&nbsp;' \
                     f'<span style="color: rgb(255, 0, 0);">{meeting_adress}</span>&nbsp;召开</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;该信息为您送来了本次会议的资料，包括&nbsp;<span style="color: rgb(255, 0, 0);">会议文件&nbsp;</span>的汇总和&nbsp;<span style="color: rgb(255, 0, 0);">议题目录</span>。</p>' \
                     f'<p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 详情请见附件内容！</p><p><br/></p><p><br/></p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
                     f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}</p><p><br style="white-space: normal;"/></p><p><br/></p>'

        file_path = [{"file_name": f"{file_name}-会议资料.pdf", "file_path": pdf_path.replace(os.getcwd(), '')},
                     {"file_name": f"{file_name}-会议目录.xlsx", "file_path": (file_path + f"/{file_name}-会议目录.xlsx").replace(os.getcwd(), '')}]
        user_obj = User.objects.filter(Q(group_id="1") | Q(group_id="2"))
        meet_people_obj = Staffing.objects.get(station='开会按钮可见').post_personnel.all()
        for t in user_obj:
            if t in meet_people_obj:
                real_name_list.append(t.real_name)
                job_num_list.append(t.job_number)
                if t.mobile.strip():
                    mobiles.append(t.mobile)
        content = '您好！%s 将于 %s 在 %s 召开, 请准时参加！' % (
            file_name, str(meeting_time).split(".")[0][:-3], meeting_adress)
        mobiles = list(set(mobiles))
        if int(notification):
            res = send_mssage(mobiles, content)

        unique = uuid.uuid4()

        InboxInfo_obj = InboxInfo.objects.create(
            content=message_content,
            plain_text=f'尊敬的院领导： 您好！{file_name}将于{str(meeting_time).split(".")[0][:-3]}在{meeting_adress}召开，该信息为您送来了本次会议的资料，包括：会议文件的汇总和，议题目录， 详情请见附件内容;  {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}',
            title=file_name,
            accessory_uuid=unique,
            is_draft= False,
            proposer=request.user
        )
        for i in job_num_list:
            user_obj = User.objects.get(job_number=i)
            InboxInfoPeople.objects.create(
                inbox_id=InboxInfo_obj,
                recipient=user_obj,
                recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>"
            )

        achments_objs = Topicsattachments.objects.filter(topics_number=InboxInfo_obj.accessory_uuid)
        for achments_obj in achments_objs:
            achments_obj.watch_users.add(InboxInfo_obj.proposer)
            for r in InboxInfo_obj.inboxinfopeople_set.all():
                if r.audit_people not in achments_obj.watch_users.all():
                    achments_obj.watch_users.add(r.audit_people)

        for ttt in file_path:
            Topicsattachments.objects.create(
                topics_number=unique,
                file_size='',
                file_path=ttt["file_path"].replace("_numbered", ""),
                uploader=request.user.real_name,
                uploader_user=request.user,
                file_type='1',
                pdf_path=ttt["file_path"].replace("_numbered", ""),
                file_name=ttt["file_name"],
                source='yx'
            )

        for T in json.loads(id_list):
            Top_obj = Topics.objects.get(id=int(T))
            Top_obj.meetings_num = meet_num
            Top_obj.iss_year = now_year
            Top_obj.is_meeting = 'b'
            Top_obj.state = 'metting'
            Top_obj.save()

            if iss_type == "yb":
                topic_meeting.objects.create(meet_number=meet_num, topic_type=Top_obj.type, meet_time=meeting_time, topic_year=Top_obj.iss_year, topic=Top_obj)

        if iss_type == "db":
            for ji in all_db_data_list:
                DbTopObj = Topics.objects.get(id=int(ji[-2]))
                topic_meeting.objects.create(meet_number=meet_num, topic_type=DbTopObj.type, meet_time=meeting_time, topic_year=DbTopObj.iss_year, topic=DbTopObj)

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 公文发文
class dispatch(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        now_time = datetime.now().strftime("%Y")
        try:
            a = Sequence.objects.get(type='a', topic_year=now_time)
            a_next_sequence = a.next_sequence
        except Exception as a:
            a = Sequence.objects.get(type='a')
            a_next_sequence = '1'
            a.sequence = '0'
            a.next_sequence = '1'
            a.topic_year = now_time
            a.save()

        try:
            b = Sequence.objects.get(type='b', topic_year=now_time)
            b_next_sequence = b.next_sequence
        except Exception as b:
            b = Sequence.objects.get(type='b')
            b_next_sequence = '1'
            b.sequence = '0'
            b.next_sequence = '1'
            b.topic_year = now_time
            b.save()

        try:
            c = Sequence.objects.get(type='c', topic_year=now_time)
            c_next_sequence = c.next_sequence
        except Exception as c:
            c = Sequence.objects.get(type='c')
            c_next_sequence = '1'
            c.sequence = '0'
            c.next_sequence = '1'
            c.topic_year = now_time
            c.save()

        try:
            d = Sequence.objects.get(type='d', topic_year=now_time)
            d_next_sequence = d.next_sequence
        except Exception as d:
            d = Sequence.objects.get(type='d')
            d_next_sequence = '1'
            d.sequence = '0'
            d.next_sequence = '1'
            d.topic_year = now_time
            d.save()

        try:
            e = Sequence.objects.get(type='e', topic_year=now_time)
            e_next_sequence = e.next_sequence
        except Exception as e:
            e = Sequence.objects.get(type='e')
            e_next_sequence = '1'
            e.sequence = '0'
            e.next_sequence = '1'
            e.topic_year = now_time
            e.save()

        try:
            f = Sequence.objects.get(type='f', topic_year=now_time)
            f_next_sequence = f.next_sequence
        except Exception as f:
            f = Sequence.objects.get(type='f')
            f_next_sequence = '1'
            f.sequence = '0'
            f.next_sequence = '1'
            f.topic_year = now_time
            f.save()

        try:
            g = Sequence.objects.get(type='g', topic_year=now_time)
            g_next_sequence = g.next_sequence
        except Exception as g:
            g = Sequence.objects.get(type='g')
            g_next_sequence = '1'
            g.sequence = '0'
            g.next_sequence = '1'
            g.topic_year = now_time
            g.save()

        try:
            h = Sequence.objects.get(type='h', topic_year=now_time)
            h_next_sequence = h.next_sequence
        except Exception as h:
            h = Sequence.objects.get(type='h')
            h_next_sequence = '1'
            h.sequence = '0'
            h.next_sequence = '1'
            h.topic_year = now_time
            h.save()

        try:
            i = Sequence.objects.get(type='i', topic_year=now_time)
            i_next_sequence = i.next_sequence
        except Exception as i:
            i = Sequence.objects.get(type='i')
            i_next_sequence = '1'
            i.sequence = '0'
            i.next_sequence = '1'
            i.topic_year = now_time
            i.save()

        returnData = {'code': 200, 'message': '获取成功！', 'number': str(uuid.uuid1()),
                      'type': {'a': a_next_sequence, 'b': b_next_sequence, 'c': c_next_sequence, 'd': d_next_sequence,
                               'e': e_next_sequence, 'f': f_next_sequence, 'g': g_next_sequence, 'h': h_next_sequence, 'i': i_next_sequence}}

        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        leaders = Staffing.objects.get(station="院领导").post_personnel.all()
        qf_leaders = User.objects.filter(group_id=1, is_delete=False)
        sign_jointly = User.objects.filter(group_id__in=[1, 2], is_delete=False)
        return render(request, "personal_center/dispatch.html",
                      {'realname': real_name, 'position': position, 'department': department, "returnData": returnData,
                       "company_list": company_list, "leaders": leaders, 'qf_leaders': qf_leaders, 'sign_jointly': sign_jointly})


# 公文详情
class document_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        attention = request.GET.get("attention", None)
        receiving = request.GET.get("receiving", None)
        id = request.GET.get('id', None)
        sy_flag = ""
        if attention:
            sy_flag = True
        receiving = 'true' if receiving else  'false'

        conference_memo_obj = ConferenceMemo.objects.get(id=id)

        audit_dic, audit_list = {}, []
        int_to_str = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六"}
        if conference_memo_obj.type not in ["a", "c"]:
            ConfeObj = conference_memo_obj.conferencememoauditrecord_set.filter(state='draft').order_by("update_time")
            if ConfeObj.count():
                for kk in range(ConfeObj.count()+1):
                    dict_name = {"ApproveText": f"审批详情{int_to_str[kk + 1]}"}
                    if kk < ConfeObj.count() and kk == 0:
                        print("===========================1", kk)
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__lte=AppaveTime).order_by("update_time")
                    elif kk == ConfeObj.count():
                        print("===========================2", kk)
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(Q(create_time__gt=ConfeObj[kk - 1].update_time) | Q(state='unaudit')).order_by("update_time")
                    else:
                        print("===========================3", kk)
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__gt=ConfeObj[kk - 1].update_time, update_time__lte=AppaveTime).order_by("update_time")

                    for audit_obj in SearchObj:
                        if audit_obj.node in dict_name:
                            dict_name[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                              'state': audit_obj.state,
                                                              'node': audit_obj.node, 'state_display': audit_obj.get_state_display(),
                                                              'node_display': audit_obj.get_node_display(),
                                                              'audit_note': audit_obj.audit_note,
                                                              'audit_time': audit_obj.update_time.strftime(
                                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                              'signature_picture': '/media/' + str(
                                                                  audit_obj.audit_people.signature_picture) if (
                                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                        else:
                            dict_name[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node, 'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    audit_list.append(dict_name)

            else:
                for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node, 'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node, 'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        else:
            for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        is_stop = 'true' if conference_memo_obj.state not in ['draft', 'seven', 'cancel', 'stop', 'recall'] and conference_memo_obj.apply_user == request.user else 'flase'
        if 'BGS' in audit_dic:
            for jj in audit_dic['BGS']:
                if jj["state_display"] == '同意':
                    jj["state_display"] = '已审核'

        return render(request, "personal_center/document_detail.html",
                      {'realname': real_name, 'position': position, 'department': department, "sy_flag": sy_flag, "receiving": receiving, "audit_dic": audit_dic, "audit_list": audit_list, "is_stop": is_stop, "conference_memo_obj": conference_memo_obj})


# 我的拟稿
class my_draft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/my_draft.html",
                      {'realname': real_name, 'position': position, 'department': department, "table_name": "administrative_conferencememo"})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = user.conferencememo_set.filter(Q(document_number__contains=search_data) | Q(conference_memo_text__contains=search_data)).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'document_number': obj.document_number,
             'conference_memo_text': obj.conference_memo_text,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state,
             'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'apply_user': obj.apply_user.real_name,
             'company': obj.apply_user.company.name,
             'url': f"<a href='/administrative/conference_memo_draft_view?id={obj.id}'>编辑</a>" if obj.state == 'draft' else f"<a href='document_detail.html?id={obj.id}'>查看</a>",
             'state_display': obj.get_state_str()
             } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class document_delete(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = ConferenceMemo.objects.get(id=int(flow_id))
        if obj.state not in ['draft', 'six']:
            returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        MakeCopy.objects.filter(type='b', process_id=flow_id).delete()
        obj.correspondencerecord_set.all().delete()
        obj.correspondencepeople_set.all().delete()
        obj.current_audit_users.clear()
        obj.audit_users_already.clear()
        obj.delete()
        returnDict = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 公文待办、已办
class DocumentManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/DocumentManagement.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        tab = request.POST.get("tab", 'audit')  # audit 我的待办 already 我的已办
        if tab == 'audit':
            objs = user.conference_memo_users.all().order_by('-create_time')
        else:
            objs = user.conference_memo_already_audit_users.all().order_by('-create_time')
        data_list = [
            {'id': obj.id, 'document_number': obj.document_number, 'conference_memo_text': obj.conference_memo_text,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'apply_user': obj.apply_user.real_name, 'company': obj.apply_user.company.name, 'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class document_approve(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        con_id = request.GET.get("id", '')
        conference_memo_obj = ConferenceMemo.objects.get(id=con_id)

        audit_dic, audit_list = {}, []
        int_to_str = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六"}
        if conference_memo_obj.type not in ["a", "c"]:
            ConfeObj = conference_memo_obj.conferencememoauditrecord_set.filter(state='draft').order_by("update_time")
            if ConfeObj.count():
                for kk in range(ConfeObj.count() + 1):
                    dict_name = {"ApproveText": f"审批详情{int_to_str[kk + 1]}"}
                    if kk < ConfeObj.count() and kk == 0:
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__lte=AppaveTime).order_by("update_time")
                    elif kk == ConfeObj.count():
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(Q(create_time__gt=ConfeObj[kk - 1].update_time) | Q(state='unaudit')).order_by("update_time")
                    else:
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__gt=ConfeObj[kk - 1].update_time, update_time__lte=AppaveTime).order_by("update_time")

                    for audit_obj in SearchObj:
                        if audit_obj.node in dict_name:
                            dict_name[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                              'state': audit_obj.state, 'node': audit_obj.node,
                                                              'state_display': audit_obj.get_state_display(),
                                                              'node_display': audit_obj.get_node_display(),
                                                              'audit_note': audit_obj.audit_note,
                                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                        else:
                            dict_name[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state, 'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    audit_list.append(dict_name)

            else:
                for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state, 'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        else:
            for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        if 'BGS' in audit_dic:
            for jj in audit_dic['BGS']:
                if jj["state_display"] == '同意':
                    jj["state_display"] = '已审核'
        return render(request, "personal_center/document_approve.html",
                      {'realname': real_name, 'position': position, 'department': department, 'con_obj': conference_memo_obj, "audit_dic": audit_dic, "audit_list": audit_list})

    def post(self, request):
        id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = ConferenceMemoAuditRecord.objects.filter(id=id)
        st = obj.update(state=state)
        if st:
            returnDict = {'code': 200, 'success': '撤回成功！'}
        else:
            returnDict = {'code': 400, 'success': '撤回失败！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 内部收文
class my_receipt(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/my_receipt.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'accept')  # accept 未接受 accepted 已接收
        if tab == 'accept':
            objs = user.conferencememopeople_set.filter(state='accept').order_by("-create_time")
        else:
            objs = user.conferencememopeople_set.filter(state='accepted').order_by("-create_time")
        data_list = [
            {'id': obj.notice_id.id, 'type': obj.notice_id.get_type_str(),
             'document_number': obj.notice_id.document_number,
             # 'state': obj.get_state_str(),
             'title': obj.notice_id.conference_memo_text,
             'create_time': str(obj.notice_id.create_time).split('.')[0][:-3],
             'apply_user': obj.notice_id.apply_user.real_name,
             'department': obj.notice_id.apply_user.department} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OfficialDocumentsListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        # 换成上级来文的列表
        return render(request, "personal_center/official_documents_list_view.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = OfficialDocuments.objects.filter(Q(title__contains=search_data) |
                                                  Q(recive_number__contains=search_data) |
                                                  Q(send_company__contains=search_data), apply_user=user).order_by('-create_time')

        review_list, distributed, return_list, circulation, end_list, cancel_list, stop_list, recall_list = [], [], [], [], [], [], [], []
        for obj in objs:
            one_dict = {'id': obj.id, 'title': obj.title, 'send_company': obj.send_company,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.get_state_str(), 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'send_number': obj.send_number, 'recive_number': obj.recive_number, 'state_display': obj.get_state_str(),
             "url": f"<a href='examinationDetail.html?id={obj.id}'>查看</a> | <a href='javascript:;' id='{obj.id}' onclick='model_inlone(this.id)'>备注</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.type == 'stop' else f"<a href='examinationDetail.html?id={obj.id}'>查看</a> | <a href='javascript:;' id='{obj.id}' onclick='model_inlone(this.id)'>备注</a>"}
            if obj.type == "g":
                distributed.append(one_dict)
            elif obj.type == "f":
                return_list.append(one_dict)
            elif obj.type == "e":
                end_list.append(one_dict)
            elif obj.type == "d":
                circulation.append(one_dict)
            elif obj.type == "cancel":
                cancel_list.append(one_dict)
            elif obj.type == "stop":
                stop_list.append(one_dict)
            elif obj.type == "recall":
                recall_list.append(one_dict)
            else:
                review_list.append(one_dict)
        data_list = review_list + return_list + distributed + stop_list + recall_list + cancel_list + circulation + end_list
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 来文-来文拟稿-我的拟稿
class superiorJeremy(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        today_data = time.strftime("%Y-%m-%d", time.localtime())
        today = datetime.now().date()
        lw_count = today_data + "-" + str(OfficialDocuments.objects.filter(~Q(state='recall'), create_time__gt=today).count() + 1)
        topics_file_objs = Topicsattachments.objects.filter(topics_number=lw_count)
        zhengwen = [{'file_name': topics_file_obj.file_path.name.split("/")[-1],
                     'id': topics_file_obj.id,
                     'file_size': topics_file_obj.file_size, 'uploader': request.user.real_name,
                     "pdf_path": topics_file_obj.pdf_path,
                     'upload_time': topics_file_obj.create_time.strftime("%Y-%m-%d %H:%M")} for topics_file_obj in
                    topics_file_objs if topics_file_obj.file_type == "0"]
        fujian = [{'file_name': topics_file_obj.file_path.name.split("/")[-1],
                   'id': topics_file_obj.id,
                   'file_size': topics_file_obj.file_size, 'uploader': request.user.real_name,
                   "pdf_path": topics_file_obj.pdf_path,
                   'upload_time': topics_file_obj.create_time.strftime("%Y-%m-%d %H:%M")} for topics_file_obj in
                  topics_file_objs if topics_file_obj.file_type == "1"]
        charge_flag = True if request.user == Company.objects.get(id=80).head_people else False
        leaders_obj = User.objects.filter(group_id__in=[1, 2])
        return render(request, "personal_center/superiorJeremy.html",
                      {'realname': real_name, 'position': position, 'department': department, "lw_count": lw_count, "charge_flag": charge_flag, "leaders_obj": leaders_obj,
                       "zhengwen": zhengwen, "fujian": fujian, "uuid": uuid.uuid1(), "table_name": "administrative_officialdocuments"})


# 来文-公文管理
class Jeremy_draft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/Jeremy_draft.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'audit')  # audit 我的待办 already 我的已办
        if tab == 'audit':
            objs = user.official_documents_users.all().order_by('-create_time')
        else:
            objs = user.official_documents_already_audit_users.all().order_by('-create_time')
        data_list = [
            {'id': obj.id, 'title': obj.title, 'send_company': obj.send_company,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.type, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'send_number': obj.send_number, 'recive_number': obj.recive_number, 'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 来文审批详情
class examinationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        office_id = request.GET.get("id", None)
        office_obj = OfficialDocuments.objects.get(id=int(office_id))
        if int(office_id) <= 2728:
            approve = request.GET.get("approve", None)
            approve_flag = ""
            if approve:
                approve_flag = True

            returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
            company_list = []
            for c in returndata:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)


            return render(request, "personal_center/examinationDetail.html",
                          {'realname': real_name, 'position': position, 'department': department,
                           "approve_flag": approve_flag, "company_list": company_list, "uuid": office_obj.uuid})
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in office_obj.officialdocumentsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in office_obj.officialdocumentsauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=office_obj.uuid)]

            ReceivingObj = office_obj.officialdocumentspeople_set.all()
            ReceivingList = []
            for receiving in ReceivingObj:
                ReceivingList.append({"receiving": receiving.audit_people.real_name, "time": receiving.update_time.strftime("%Y-%m-%d %H:%M"), "state": receiving.state,
                                      "signature_picture": '/media/' + str(receiving.audit_people.signature_picture) if receiving.audit_people.signature_picture else ''})

            withdrawal = "false"
            received_obj = office_obj.officialdocumentsauditrecord_set.filter(audit_people=request.user, state="audit")
            if received_obj.count():
                if received_obj.last().node == "one" and office_obj.state == "two":
                    withdrawal = "true"
                elif received_obj.last().node == "two" and office_obj.state == "three":
                    withdrawal = "true"
                elif received_obj.last().node == "three" and (office_obj.state == "three" or office_obj.state == "four"):
                    withdrawal = "true"
                elif received_obj.last().node == "four" and office_obj.state == "five":
                    withdrawal = "true"
                else:
                    withdrawal = "false"
            try:
                db_tip = Topics.objects.get(HouseToParty_id=office_obj.top_flow_id.id) if office_obj.top_flow_id else ''
            except:
                db_tip = ''

            apply_person_signature_picture, apply_person_time = "", ""
            if office_obj.top_flow_id:
                apply_person_obj = office_obj.officialdocumentsauditrecord_set.filter(node='three').first()
                apply_person_signature_picture = '/media/' + str(apply_person_obj.audit_people.signature_picture) if apply_person_obj.audit_people.signature_picture else ''
                apply_person_time = apply_person_obj.update_time.strftime("%Y-%m-%d %H:%M")

            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'apply_person_signature_picture': apply_person_signature_picture,
                       "obj": office_obj, 'audit_dic': audit_dic, "file_list": file_list, "withdrawal": withdrawal, "company_type": "yb" if office_obj.apply_user.company.id == 80 else "db",
                       'is_edit': 'true' if (office_obj.state == 'eight' and office_obj.apply_user == request.user) else 'false', 'apply_person_time': apply_person_time,
                       'is_audit': 'true' if office_obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in office_obj.current_audit_users.all() and not office_obj.topOrappave else 'false',
                       'is_stop': 'true' if office_obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == office_obj.apply_user else 'false',
                       'uuid': office_obj.uuid, 'flow_dict': flow_dict, "leader_obj": User.objects.filter(group_id__in=[1, 2]), "ReceivingList": ReceivingList, "db_tip": db_tip,
                       'file_path': Topicsattachments.objects.filter(topics_number=office_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=office_obj.uuid) else ""
                       }
            if office_obj.version == '3':
                return render(request, "personal_center/examinationDetail_version_three.html", context)
            return render(request, "personal_center/examinationDetail_new.html", context)

    def post(self, request):
        id = request.POST.get("id", None)
        state = request.POST.get("state", None)     # 撤回操作
        obj = OfficialDocuments.objects.filter(id=id)
        st = obj.update(state=state)
        if st:
            returnDict = {'code': 200, 'success': '撤回成功！'}
        else:
            returnDict = {'code': 400, 'success': '撤回失败！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 来文-待收-已收
class higher_addressee(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/higher_addressee.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'accept')  # accept 未接受 accepted 已接收
        if tab == 'accept':
            objs = user.officialdocumentspeople_set.filter(state='accept').order_by("-create_time")
        else:
            objs = user.officialdocumentspeople_set.filter(state='accepted').order_by("-create_time")
        record_list = [record.notice_id for record in objs]
        data_list = [
            {'id': obj.id, 'send_company': obj.send_company, 'send_number': obj.send_number,
             'recive_time': obj.recive_time.strftime("%Y-%m-%d"), 'title': obj.title,
             'state': obj.get_type_display(), 'recive_number': obj.recive_number,
             'user': obj.apply_user.real_name, 'department': obj.apply_user.company.name,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             } for obj in
            record_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": len(record_list), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class Leave_article_archive(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/Leave_article_archive.html",
                      {'realname': real_name, 'position': position, 'department': department})


class process_management1(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return_data = manage_flow().my_audit(request.user.id, request.user.real_name)

        objs = CustomerFormModule.objects.all()
        return_list = {}
        for names in objs:
            return_list[names.name] = {"data": [], "count": 0}

        for i in range(len(return_data)):
            flag = 0
            if i == 0:
                flag = 1
            if return_data[i][0] in return_list:
                return_list[return_data[i][0]]["data"].append({"type": return_data[i][1], "number": return_data[i][2], 'flag': flag})
                return_list[return_data[i][0]]["count"] += int(return_data[i][2])
        return render(request, "personal_center/process_management.html", {'realname': real_name, 'position': position, 'department': department, "return_list": return_list})

class process_management(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        types = request.GET.get("type", '')                 # 我的待办、已办、申请、搁置
        folw = request.GET.get("folw", '')                      # 议题、公文等
        page = request.GET.get("page", '')              # 页码
        page_size = request.GET.get("page_size", '')              # 每页数量
        search_data = request.GET.get("wd", '')         # 搜索关键词
        folw_type = request.GET.get("folw_type", '')            # 流程类型
        flow_name = request.GET.get("flow_name", '')            # 上级来文状态查询
        num1 = (int(page) - 1) * int(page_size)
        num2 = int(page) * int(page_size)

        if types == "我的待办":
            data_list, return_data, all_count = SearchData().search_daiban(folw, search_data, request, num1, num2)
        elif types == "我的已办":
            if flow_name:
                return_data = manage_flow().my_done(request.user.id, request.user.real_name)
                if flow_name == "1":
                    state_list = ['a', 'b', 'c', 'g', 'h']
                elif flow_name == "2":
                    state_list = ["d"]
                elif flow_name == "3":
                    state_list = ["f"]
                else:
                    state_list = ["e"]
                all_count = OfficialDocuments.objects.filter(
                    Q(title__contains=search_data) | Q(apply_user__real_name__contains=search_data) | Q(apply_user__department__contains=search_data), audit_users_already=request.user,
                    type__in=state_list).order_by("-create_time").count()
                all_data = OfficialDocuments.objects.filter(
                    Q(title__contains=search_data) | Q(apply_user__real_name__contains=search_data) | Q(apply_user__department__contains=search_data), audit_users_already=request.user,
                    type__in=state_list).order_by("-create_time")[num1:num2]
                data_list = [
                    {"title": i.title, "create_by": i.apply_user.real_name, "department": i.apply_user.department,
                     "create_time": i.officialdocumentsauditrecord_set.filter(audit_people=request.user).last().update_time.strftime("%Y-%m-%d %H:%M"), "id": i.id,
                     "node": i.get_state_str(),
                     "approved": f'<a href="javascript:;" style="color: red;">{", ".join([t.real_name for t in i.current_audit_users.all()])}</a>',
                     "url": f'/personal-center/examinationDetail.html?approve=1&id={i.id}', "admin_add": "",
                     'text': "分发" if i.type == "g" else "修改" if i.type == "f" else "审批", "types": "上级来文"} for i in all_data]
                data_list = sorted(data_list, key=lambda dat: dat["create_time"], reverse=True)
            else:
                data_list, return_data, all_count = SearchData().search_yiban(folw, search_data, request, num1, num2)
        elif types == "我的搁置":
            data_list, return_data, all_count = SearchData().search_gezhi(folw, search_data, request, num1, num2)
        else:
            data_list, return_data, all_count = SearchData().search_shenqing(folw, search_data, request, num1, num2)

        ReturnList = {}
        if return_data:
            objs = CustomerFormModule.objects.all()
            for names in objs:
                ReturnList[names.name] = {"data": [], "count": 0}

            for i in range(len(return_data)):
                flag = 0
                if i == 0:
                    flag = 1
                if return_data[i][0] in ReturnList:
                    ReturnList[return_data[i][0]]["data"].append({"type": return_data[i][1], "number": return_data[i][2], 'flag': flag})
                    ReturnList[return_data[i][0]]["count"] += int(return_data[i][2])

        for tt in range(len(data_list)):
            data_list[tt]["Serial"] = (int(page) - 1) * 20 + (tt + 1)

        page_all_number = all_count//int(page_size) + 1 if all_count%int(page_size)>0 else all_count//20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page)-1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page)-2, int(page)-1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += ["...",  page_all_number - 5,  page_all_number - 4,  page_all_number - 3, page_all_number - 2, page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj+1)

        views_range_start = (int(page)-1) * 20 + 1
        views_range_end = (int(page) - 1) * 20 + 20
        return render(request, "personal_center/process_management.html", {'realname': real_name, 'position': position, 'department': department, "return_list": ReturnList,
                    "data": data_list, "folw_type": folw_type, "folw": folw, "types": types, "totals": all_count, "flow_name": flow_name, "page_list": page_list, "pages": int(page),
                    "page_size": int(page_size), "page_all_number": page_all_number, "wd": search_data, "views_range_start": views_range_start, "views_range_end": views_range_end})


class primary_pdf(View):
    def get(self, request):
        id_list = request.GET.get("iss_id_list", None)
        file_name = request.GET.get("file_name", None)

        id_str = ''.join([str(i) for i in json.loads(id_list)])
        FilePath = os.getcwd() + f"/media/files/{file_name}.txt"
        if os.path.exists(FilePath):
            with open(FilePath, "r+", encoding="utf-8") as FF:
                iddata = FF.read()
                if id_str != iddata.strip():
                    returnData = {'code': 404, 'message': '成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            returnData = {'code': 404, 'message': '成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file"
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料.pdf"  # PDF 议题资料路径

        if not os.path.exists(pdf_path):
            returnDict = {'code': 404, 'status': 'success'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 200, 'status': 'success', "file_path": pdf_path}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class download_pdf(View):
    def get(self, request):
        pdf_path = request.GET.get("pdf_path", None)
        def down_chunk_file_manager(pdf_path, chuck_size=1024):
            """
            文件分片下发
            :param file_path:
            :param chuck_size:
            :return:
            """
            pdf_path = pdf_path.replace(".pdf", '') + "_numbered.pdf"
            with open(pdf_path, "rb") as file:
                while True:
                    chuck_stream = file.read(chuck_size)
                    if chuck_stream:
                        yield chuck_stream
                    else:
                        break

        response = StreamingHttpResponse(down_chunk_file_manager(pdf_path.replace("_numbered", "")))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(pdf_path.split("/")[-1]))
        return response


class Issue_modify(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        ids = request.GET.get("id", None)
        obj = Topics.objects.get(id=int(ids))
        objs_count = 'true' if Topics.objects.get(id=int(ids)).topicsauditrecord_set.filter(node='PG').count() else 'false'
        objs_dict = {
            'topics_text': base64.b64decode(obj.topics_text).decode(),
            'topics_basis': base64.b64decode(obj.topics_basis).decode(),
            'solution': base64.b64decode(obj.solution).decode() if obj.solution != "空" else "",
            'db_topics_text': base64.b64decode(obj.db_topics_text).decode() if obj.db_topics_text else "",
            'db_topics_basis': base64.b64decode(obj.db_topics_basis).decode() if obj.db_topics_basis else "",
            'db_solution': base64.b64decode(obj.db_solution).decode() if obj.db_solution else "",
        }

        audit_dic = {}
        for audit_obj in obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        leaders = User.objects.filter(group_id=2, is_delete=False)
        return render(request, "personal_center/Issue_modify.html", {'realname': real_name, 'position': position, 'department': department, "company_list": company_list,
                    "objs_count": objs_count, "obj": obj, "objs_dict": objs_dict, "audit_dic": audit_dic, "zbb_flag": "true" if request.user.company.id == 9 else "false", "leaders": leaders})


class car_recommit(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        all_list = User.objects.filter(group_id__in=(1, 2)).values_list('job_number', 'real_name')
        returnList = []
        for i in all_list:
            returnList.append({'job_number': i[0], "name": i[1]})
        return render(request, "personal_center/car_recommit.html",
                      {'realname': real_name, 'position': position, 'department': department, "returnList": returnList})


class refer_back(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        id = request.GET.get('id', None)
        conference_memo_obj = ConferenceMemo.objects.get(id=id)

        audit_dic, audit_list = {}, []
        int_to_str = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六"}
        if conference_memo_obj.type not in ["a", "c"]:
            ConfeObj = conference_memo_obj.conferencememoauditrecord_set.filter(state='draft').order_by("update_time")
            if ConfeObj.count():
                for kk in range(ConfeObj.count()):
                    dict_name = {"ApproveText": f"审批详情{int_to_str[kk + 1]}"}
                    if kk < ConfeObj.count() and kk == 0:
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__lte=AppaveTime).order_by("update_time")
                    elif kk == ConfeObj.count():
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(Q(create_time__gt=ConfeObj[kk - 1].update_time) | Q(state='unaudit')).order_by("update_time")
                    else:
                        AppaveTime = ConfeObj[kk].update_time
                        SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'), update_time__gt=ConfeObj[kk - 1].update_time, update_time__lte=AppaveTime).order_by("update_time")

                    for audit_obj in SearchObj:
                        if audit_obj.node in dict_name:
                            dict_name[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                              'state': audit_obj.state, 'node': audit_obj.node,
                                                              'state_display': audit_obj.get_state_display(),
                                                              'node_display': audit_obj.get_node_display(),
                                                              'audit_note': audit_obj.audit_note,
                                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                        else:
                            dict_name[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state, 'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    audit_list.append(dict_name)

            else:
                for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state, 'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        else:
            for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        is_stop = 'true' if conference_memo_obj.state not in ['draft', 'seven', 'cancel', 'stop', 'recall'] and conference_memo_obj.apply_user == request.user else 'flase'
        if 'BGS' in audit_dic:
            for jj in audit_dic['BGS']:
                if jj["state_display"] == '同意':
                    jj["state_display"] = '已审核'

        returnData = {'code': 200, 'message': '获取成功！', 'number': str(uuid.uuid1())}
        return render(request, "personal_center/refer_back.html",
                      {'realname': real_name, 'position': position, 'department': department, "returnData": returnData, 'audit_dic': audit_dic, "audit_list": audit_list, "is_stop": is_stop})


class download_excel(View):
    def get(self, request):
        id_list = request.GET.get("iss_id_list", None)
        file_name = request.GET.get("file_name", None)
        iss_type = request.GET.get("iss_type", None)

        id_str = ''.join([str(i) for i in json.loads(id_list)])
        FilePath = os.getcwd() + f"/media/files/{file_name}.txt"
        if os.path.exists(FilePath):
            with open(FilePath, "r+", encoding="utf-8") as FF:
                iddata = FF.read()
                if id_str != iddata.strip():
                    returnData = {'code': 404, 'message': '成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            returnData = {'code': 404, 'message': '成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict = [], [], [], {}, {}, {}
        if iss_type == 'yb':
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/yb/{file_name}-会议目录.xlsx"
            if not os.path.exists(file_path):
                returnDict = {'code': 404, 'status': 'success'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            returnDict = {'code': 200, 'status': 'success', "file_path": file_path}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif iss_type == 'db':
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/db/{file_name}-会议目录.xlsx"
            if not os.path.exists(file_path):
                returnDict = {'code': 404, 'status': 'success'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            returnDict = {'code': 200, 'status': 'success', "file_path": file_path}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/xz/{file_name}-会议目录.xlsx"
            if not os.path.exists(file_path):
                returnDict = {'code': 404, 'status': 'success'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            returnDict = {'code': 200, 'status': 'success', "file_path": file_path}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class download_excel_file(View):
    def get(self, request):
        file_path = request.GET.get("file_path", None)
        file_name = request.GET.get("file_name", None)
        def down_chunk_file_manager(pdf_path, chuck_size=1024):
            """
            文件分片下发
            :param file_path:
            :param chuck_size:
            :return:
            """
            with open(pdf_path, "rb") as file:
                while True:
                    chuck_stream = file.read(chuck_size)
                    if chuck_stream:
                        yield chuck_stream
                    else:
                        break

        # if not is_zhuijia:
        response = StreamingHttpResponse(down_chunk_file_manager(file_path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment; filename*=UTF-8''{}".format(
            escape_uri_path(file_path.split("/")[-1]))
        return response


def get_next_month_start(month_str=None):
    # 获取下一个月的第一天
    '''
    param: month_str 月份，2022-04
    '''
    # return: 格式 %Y-%m-%d
    if not month_str:
        month_str = datetime.now().strftime('%Y-%m')
    year, month = int(month_str.split('-')[0]), int(month_str.split('-')[1])
    if month == 12:
        year += 1
        month = 1
    else:
        month += 1
    return "%4d-%02d-01" % (year, month)


class SealApplyListView(View):
    def get(self, request):
        context = {'realname': request.user.real_name, 'position': request.user.post}
        return render(request, 'personal_center/seal_apply_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = user.sealapply_set.filter(Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data) | Q(seal_name__contains=search_data)).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'number': obj.number,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state,
             'seal_name':obj.seal_name,
             'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'matter_type_text': obj.matter_type_text,
             'url': f"<a href='seal_apply_draft_view?id={obj.id}'>编辑</a>" if obj.state == 'draft' else (f"<a href='seal_apply_detail_view?id={obj.id}'>查看</a>" if obj.create_time.strftime("%Y-%m-%d %H:%M") < '2024-06-01 00:00' or obj.FileType == '2' else (f"<a href='seal_apply_detail_view?id={obj.id}'>查看</a> | <a href='javascript:;' style='color: #CFCFCF;'>上传协议</a>" if obj.whether_upload == '1' else f"<a href='seal_apply_detail_view?id={obj.id}'>查看</a> | <a href='javascript:;' onclick='online_tag(\"yysq\", \"\", \"\", \"\", \"\", \"{obj.fj_number}\")'>上传协议</a>")),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class delete_seal_flow(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = SealApply.objects.get(id=int(flow_id))
        if obj.state not in ['draft', 'six']:
            returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        MakeCopy.objects.filter(type='a', process_id=flow_id).delete()
        obj.sealapplyauditrecord_set.all().delete()
        obj.audit_users_already.clear()
        obj.current_audit_users.clear()
        obj.delete()
        returnDict = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SealApplyIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        seal_obj = seal.objects.all()
        seal_list = []
        for tt in seal_obj:
            seal_list.append({"id": tt.id, "seal_name": tt.seal_name})

        quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user, take_effect_time__lte=datetime.now().strftime("%Y-%m-%d"), lose_efficacy_time__gte=datetime.now().strftime("%Y-%m-%d"))

        str_list, SealList, JudgmentDictionary = [], [], {}
        if quick_obj.count():
            Quick = 'true'
            for obj in quick_obj:
                for i in json.loads(obj.reason):
                    if seal.objects.get(id=i["yinzhang"]).seal_name not in SealList:
                        SealList.append(seal.objects.get(id=i["yinzhang"]).seal_name)
                    if i['neirong'].strip() and i['neirong'].strip() not in str_list:
                        str_list.append(i['neirong'].strip())

                    if i['neirong'].strip() in JudgmentDictionary:
                        JudgmentDictionary[i['neirong'].strip()].append(seal.objects.get(id=i["yinzhang"]).seal_name)
                    else:
                        JudgmentDictionary[i['neirong'].strip()] = [seal.objects.get(id=i["yinzhang"]).seal_name]

        else:
            Quick = 'false'

        if request.user.company.id in [3, 80, 8]:
            leaders_obj = User.objects.filter(group__id__in=[1, 2])
        else:
            leaders_obj = User.objects.filter(group__id=2)

        bgs_flag = 'true' if request.user.company.id == 80 else 'false'
        return render(request, "personal_center/seal_applicant_index.html", {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid1(),
                                                                             'now_date': datetime.now().strftime("%Y-%m-%d"), "seal_obj": seal_obj, "Quick": Quick,
                                                                             "leaders_obj": leaders_obj, "seal_list": seal_list, "str_list": str_list, "SealList": SealList,
                                                                             "JudgmentDictionary": JudgmentDictionary, 'bgs_flag': bgs_flag})

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        servings = request.POST.get('servings', 1)
        seal_name = request.POST.get('seal_name', None)
        credentials = request.POST.get('credentials', None)
        matter_type_text = request.POST.get('matter_type_text', None)
        fj_number = request.POST.get('fj_number', None)
        note = request.POST.get('note', '')
        YDetail = request.POST.get('YDetail', '')
        leader_select = request.POST.get('leader_select', None)                 # 分管领导
        FileType = request.POST.get('FileType', '')
        admin_flag = request.POST.get('admin', '')
        offline_printing = request.POST.get('offline_printing', '')
        b_step = User.objects.get(id=int(leader_select))
        try:
            RecordAndPush().OperationRecords(request, "用印审批")
        except:
            pass
        QuickApplication = False
        quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user, lose_efficacy_time__gte=datetime.now())
        if quick_obj.count():
            if matter_type_text == "其他":
                matter_type_text = YDetail
            else:
                QuickApplication = True

        if id:
            obj = SealApply.objects.get(id=int(id))
            obj.is_fast = QuickApplication
            obj.seal_name = seal_name
            obj.note = note
            obj.FileType = FileType
            obj.matter_type_text = matter_type_text
            obj.fg_id = leader_select
            obj.credentials = credentials if credentials != 'undefined' else ''
            obj.fj_number = fj_number
            obj.offline_printing = offline_printing
            obj.servings = int(servings)
            obj.save()
            if not admin_flag:
                obj.current_audit_users.clear()
                obj.sealapplyauditrecord_set.filter(state='unaudit').delete()
                MakeCopy.objects.filter(process_id=obj.id, type='a').delete()
        else:
            obj = SealApply.objects.create(number='', apply_user=user, is_fast=QuickApplication, seal_name=seal_name, note=note, matter_type_text=matter_type_text, credentials=credentials if credentials != 'undefined' else '', fj_number=fj_number,
                                           servings=int(servings), FileType=FileType, fg_id=leader_select, offline_printing=offline_printing)

        if offline_printing == '1':
            obj.offline_printing = '1'
            obj.state = 'five'
            obj.save()
            MakeCopy.objects.create(recipient=Company.objects.get(id=3).head_people, process_id=obj.id)
            returnDict = {'code': 200, 'message': '创建成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if not admin_flag:
            dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
            yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']

            one_appave = user.company.head_people

            sq_list = seal_name.split(', ')
            dw_flag, yb_flag = False, False
            for sq1 in sq_list:
                if sq1 in dw_list:
                    dw_flag = True
                if sq1 in yb_list:
                    yb_flag = True

            if QuickApplication:
                # 获取当前申请快捷用印事由的授权类型是”法人“还是”分管“
                AuthorizaObj = QuickAuthorizationApplicationCategory.objects.filter(authorized_person=request.user, category=matter_type_text.strip())
                level_flag = True
                b_flag = True
                obj.leval = AuthorizaObj.first().level
                obj.authorization_type = AuthorizaObj.first().quick.authorization_type
                audit_note_text = ''
                if matter_type_text == '体检协议':
                    audit_note_text = '体检科协议由体检科自行归档保管。'
                if AuthorizaObj.first().quick.authorization_type == '1':
                    if AuthorizaObj.first().level == '2':               # 分管领导、法人自动审批
                        if one_appave != user:
                            SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=one_appave, parent_id=obj)
                            obj.current_audit_users.add(one_appave)
                            obj.state = 'one'
                            level_flag = False
                        if level_flag:
                            obj_state = 'audit'
                        else:
                            obj_state = 'unaudit'
                        SealApplyAuditRecord.objects.create(node='B', state=obj_state, audit_people=b_step, parent_id=obj, audit_note=audit_note_text)
                        SealApplyAuditRecord.objects.create(node='ys', state=obj_state, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
                        MakeCopy.objects.create(recipient=b_step, process_id=obj.id, type='a')
                        MakeCopy.objects.create(recipient=Staffing.objects.get(station='院长').post_personnel.all().first(), process_id=obj.id, type='a')

                    elif AuthorizaObj.first().level == '3':             # 分管领导、法人、科主任自动审批
                        if one_appave != user:
                            SealApplyAuditRecord.objects.create(node='C/D', state='audit', audit_people=one_appave, parent_id=obj)
                            MakeCopy.objects.create(recipient=one_appave, process_id=obj.id, type='a')
                        SealApplyAuditRecord.objects.create(node='B', state='audit', audit_people=b_step, parent_id=obj)
                        SealApplyAuditRecord.objects.create(node='ys', state='audit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
                        MakeCopy.objects.create(recipient=b_step, process_id=obj.id, type='a')
                        MakeCopy.objects.create(recipient=Staffing.objects.get(station='院长').post_personnel.all().first(), process_id=obj.id, type='a')

                    else:
                        if one_appave != user and request.user.group.id != 2:
                            SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=one_appave, parent_id=obj)
                            obj.current_audit_users.add(one_appave)
                            obj.state = 'one'
                            level_flag = False

                        if one_appave != user and request.user.group.id != 2:
                            SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=one_appave,
                                                                parent_id=obj)
                            obj.current_audit_users.add(one_appave)
                            obj.state = 'one'
                            level_flag = False

                        if b_step != user:
                            SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=b_step, parent_id=obj)
                            SealApplyAuditRecord.objects.create(node='ys', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)

                            if level_flag:
                                obj.current_audit_users.add(b_step)
                                obj.state = 'two'
                                level_flag = False
                                b_flag = False
                        else:
                            SealApplyAuditRecord.objects.create(node='B', state='audit', audit_people=b_step, parent_id=obj)
                            SealApplyAuditRecord.objects.create(node='ys', state='audit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)

                else:
                    if AuthorizaObj.first().level == '2':
                        if one_appave != user:
                            SealApplyAuditRecord.objects.create(node='C/D', state='audit', audit_people=one_appave, parent_id=obj)
                            MakeCopy.objects.create(recipient=one_appave, process_id=obj.id, type='a')
                        SealApplyAuditRecord.objects.create(node='B', state='audit', audit_people=b_step, parent_id=obj)
                        MakeCopy.objects.create(recipient=b_step, process_id=obj.id, type='a')
                    else:
                        if one_appave != user:
                            SealApplyAuditRecord.objects.create(node='C/D', state='audit', audit_people=one_appave, parent_id=obj)
                            obj.current_audit_users.add(one_appave)
                            obj.state = 'one'
                            level_flag = False
                        obj_state = 'unaudit'
                        if level_flag:
                            obj_state = 'audit'
                            MakeCopy.objects.create(recipient=b_step, process_id=obj.id, type='a')
                        SealApplyAuditRecord.objects.create(node='B', state=obj_state, audit_people=b_step, parent_id=obj)


                typess = True
                if FileType == "1":
                    sjk_obj = Company.objects.get(id=22).head_people
                    SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=sjk_obj, parent_id=obj)
                    if sjk_obj != user and level_flag:
                        typess = False
                        level_flag = False
                        obj.current_audit_users.add(sjk_obj)
                        obj.state = 'nine'
                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                    if typess and level_flag and b_flag:
                        obj.current_audit_users.add(BGS_appave)
                        obj.state = 'four'
                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                    if typess and level_flag and b_flag:
                        obj.current_audit_users.add(BGS_appave)
                        obj.state = 'four'
                obj.save()

            else:
                flag, four_flag = True, False
                if one_appave != user:
                    SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=one_appave, parent_id=obj)
                    obj.current_audit_users.add(one_appave)
                    obj.state='one'
                    flag = False

                if request.user.company.id != 80:
                    SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=b_step, parent_id=obj)
                    if flag:
                        obj.current_audit_users.add(b_step)
                        obj.state = 'two'

                if FileType == "1":
                    sjk_obj = Company.objects.get(id=22).head_people
                    SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=sjk_obj, parent_id=obj)
                    if not obj.current_audit_users.all().count():
                        obj.current_audit_users.add(sjk_obj)
                        obj.state = 'nine'

                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)

                    if not obj.current_audit_users.all().count():
                        obj.current_audit_users.add(BGS_appave)
                        obj.state = 'four'
                        four_flag = True

                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)

                    if four_flag or not obj.current_audit_users.all().count():
                        obj.current_audit_users.add(BGS_appave)
                        obj.state = 'four'

                achments_objs = Topicsattachments.objects.filter(topics_number=obj.fj_number)

                for achments_obj in achments_objs:
                    achments_obj.watch_users.add(obj.apply_user)
                    for r in obj.sealapplyauditrecord_set.all():
                        if r.audit_people not in achments_obj.watch_users.all():
                            achments_obj.watch_users.add(r.audit_people)
                obj.save()
            obj.offline_printing = '0'
            obj.save()

            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "用印审批"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.matter_type_text[:15] + "……" if len(obj.matter_type_text) > 15 else obj.matter_type_text
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SealApplyDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SealApply.objects.get(id=int(id))
        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        seal_obj = seal.objects.all()
        if request.user.company.id in [3, 80, 8]:
            leaders_obj = User.objects.filter(group__id__in=[1, 2])
        else:
            leaders_obj = User.objects.filter(group__id=2)
        BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
        dzb_obj = Company.objects.get(id=3).head_people
        flag = 'false'
        for t in main_file_list:
            if t['file_type'] == '1':
                flag = 'true'
        category_json = []
        quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user,
                                                      take_effect_time__lte=datetime.now().strftime("%Y-%m-%d"),
                                                      lose_efficacy_time__gte=datetime.now().strftime("%Y-%m-%d"))

        str_list, SealList, JudgmentDictionary = [], [], {}
        if quick_obj.count():
            Quick = 'true'
            for objs in quick_obj:
                for i in json.loads(objs.reason):
                    if seal.objects.get(id=i["yinzhang"]).seal_name not in SealList:
                        SealList.append(seal.objects.get(id=i["yinzhang"]).seal_name)
                    if i['neirong'].strip() and i['neirong'].strip() not in str_list:
                        str_list.append(i['neirong'].strip())

                    if i['neirong'].strip() in JudgmentDictionary:
                        JudgmentDictionary[i['neirong'].strip()].append(seal.objects.get(id=i["yinzhang"]).seal_name)
                    else:
                        JudgmentDictionary[i['neirong'].strip()] = [seal.objects.get(id=i["yinzhang"]).seal_name]

        else:
            Quick = 'false'

        data_dic = {'obj': obj, 'realname': request.user.real_name, 'position': request.user.post, 'department': obj.apply_user.department,
                    'main_file_list': main_file_list, 'category_json': category_json, 'Quick': Quick, 'is_voucher': 'true' if BGS_appave == request.user and obj.voucher == '0' else 'false', 'leaders_obj': leaders_obj,
                    'user_obj': User.objects.filter(group_id=1), 'dzb_obj': dzb_obj, "Bstep": int(obj.fg_id) if obj.fg_id else '', "str_list": str_list, 'SealList': SealList,
                    'uuid': obj.fj_number, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                    'state': obj.state, "seal_obj": seal_obj, "flag": flag}
        return render(request, "personal_center/seal_applicant_draft.html", data_dic)

    def post(self, request):
        process_id = request.POST.get("id", None)
        servings = request.POST.get('servings', 1)
        seal_name = request.POST.get('seal_name', None)
        credentials = request.POST.get('credentials', None)
        matter_type_text = request.POST.get('matter_type_text', None)
        fj_number = request.POST.get('fj_number', None)
        note = request.POST.get('note', '')
        YDetail = request.POST.get('YDetail', '')
        leader_select = request.POST.get('leader_select', None)  # 分管领导
        FileType = request.POST.get('FileType', '')
        QuickApplication = False
        quick_obj = request.user.company.quickauthorizationseal_set.all()
        if quick_obj.count():
            if matter_type_text == "其他":
                matter_type_text = YDetail
            else:
                QuickApplication = True

        print(servings)

        if process_id:
            obj = SealApply.objects.get(id=int(process_id))
            obj.is_fast = QuickApplication
            obj.seal_name = seal_name
            obj.note = note
            obj.FileType = FileType
            obj.matter_type_text = matter_type_text
            obj.credentials = credentials if credentials != 'undefined' else ''
            obj.fj_number = fj_number
            obj.fg_id = leader_select
            obj.servings = int(servings) if servings.strip() else 0
            obj.save()
        else:
            obj = SealApply.objects.create(number='', apply_user=request.user, is_fast=QuickApplication, seal_name=seal_name, note=note, matter_type_text=matter_type_text, fg_id=leader_select,
                                           credentials=credentials if credentials != 'undefined' else '', fj_number=fj_number, servings=int(servings) if servings.strip() else 0, FileType=FileType)
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': '保存成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SealApplyDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SealApply.objects.get(id=int(id))

        endappave = Staffing.objects.filter(station__in=('印章管理员', '党委印章管理员'))
        end_list = [i.post_personnel.all().first() for i in endappave]

        if int(id) > 782:
            audit_dic = {}
            flow_dict = {}
            for audit_obj in obj.sealapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            main_file_list, seal_flag = [], "false"
            for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number):
                if atta_obj.file_type == '3':
                    seal_flag = "true"
                main_file_list.append({"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id})

            seal_obj = seal.objects.all()
            if request.user.company.id in [3, 80, 8]:
                leaders_obj = User.objects.filter(group__id__in=[1, 2])
            else:
                leaders_obj = User.objects.filter(group__id=2)
            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            try:
                Bstep = audit_dic['B'][-1]['audit_user']
            except:
                Bstep = ''

            dzb_obj = Company.objects.get(id=3).head_people
            sjk_obj = Company.objects.get(id=22).head_people
            flag = 'false'
            for t in main_file_list:
                if t['file_type'] == '1':
                    flag = 'true'

            quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user)
            str_list, SealList, JudgmentDictionary = [], [], {}
            if quick_obj.count():
                Quick = 'true'
                for Objs in quick_obj:
                    for i in json.loads(Objs.reason):
                        if seal.objects.get(id=i["yinzhang"]).seal_name not in SealList:
                            SealList.append(seal.objects.get(id=i["yinzhang"]).seal_name)
                        if i['neirong'].strip():
                            str_list.append(i['neirong'].strip())

                        JudgmentDictionary[i['neirong'].strip()] = seal.objects.get(id=i["yinzhang"]).seal_name

            else:
                Quick = 'false'

            copy_obj = MakeCopy.objects.filter(type='a', process_id=int(id))
            copy_flag = 'ture' if copy_obj.count() else 'false'

            if obj.sealapplyauditrecord_set.filter(node="C/D"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="C/D"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["C/D"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="B"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="B"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["B"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="ys"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="ys"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["ys"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="sjk"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="sjk"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["sjk"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="BGS"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="BGS"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["BGS"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="stb"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="stb"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["stb"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YB"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YB"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YB"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YZ"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YZ"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YZ"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="audits"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="audits"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["audits"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END_2"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END_2"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END_2"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            aleard_flag = "false"
            if obj.is_fast and obj.state not in ["five", "six"]:
                if 'ys' in audit_dic and request.user.real_name == audit_dic["ys"][0]["audit_user"]:
                    aleard_flag = "true"
                if 'B' in audit_dic and request.user.real_name == audit_dic["B"][0]["audit_user"]:
                    aleard_flag = "true"
                if 'C/D' in audit_dic and request.user.real_name == audit_dic["C/D"][0]["audit_user"]:
                    aleard_flag = "true"

            data_dic = {'obj': obj, 'audit_dic': audit_dic, 'realname': request.user.real_name, 'position': request.user.post, 'department': obj.apply_user.company.name, 'SealList': SealList,
                        'main_file_list': main_file_list, 'is_edit': 'true' if obj.state == 'six' and obj.apply_user == request.user else 'false', 'Quick': Quick, 'str_list': str_list, 'sj_obj': Staffing.objects.get(station="书记").post_personnel.all().first(),
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'seven', 'eight', 'nine', 'eleven', 'twelve', 'thirteen'] and request.user in obj.current_audit_users.all() else 'false',
                        'is_voucher': 'true' if BGS_appave == request.user and obj.voucher == '0' and obj.state == 'five' else 'false', 'leaders_obj': leaders_obj, 'Bstep': Bstep, 'sjk_obj': sjk_obj, "aleard_flag": aleard_flag,
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine', 'thirteen'] and request.user == obj.apply_user else 'false', 'user_obj': Staffing.objects.get(station="院长").post_personnel.all().first(), 'dzb_obj': dzb_obj,
                        'uuid': obj.fj_number, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                        'state': obj.state, 'flow_dict': flow_dict, "seal_obj": seal_obj, "flag": flag, "copy_obj": copy_obj, "copy_flag": copy_flag, "JudgmentDictionary": JudgmentDictionary,
                        'print_flag': 'true' if (request.user in end_list) and obj.state == 'five' else 'flase', 'seal_flag': seal_flag}
            return render(request, "personal_center/seal_detail_page.html", data_dic)
        else:
            audit_dic = {}
            flow_dict = {}
            for audit_obj in obj.sealapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            if request.user.company.id == 16:  # 人事科
                user_type = '1'
            elif request.user.company.id == 14:  # 科教科
                user_type = '2'
            elif request.user.company.id == 15:  # 护理部
                user_type = '3'
            elif request.user.company.id == 13:  # 医务科
                user_type = '4'
            elif request.user.company.id == 7:  # 医务科
                user_type = '5'
            else:
                user_type = '0'
            seal_obj = seal.objects.all()
            if request.user.company.id in [3, 80, 8]:
                leaders_obj = User.objects.filter(group__id__in=[1, 2])
            else:
                leaders_obj = User.objects.filter(group__id=2)
            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            try:
                Bstep = audit_dic['B'][-1]['audit_user']
            except:
                Bstep = ''
            dzb_obj = Company.objects.get(id=3).head_people
            sjk_obj = Company.objects.get(id=22).head_people
            flag = 'false'
            for t in main_file_list:
                if t['file_type'] == '1':
                    flag = 'true'
            category_obj = request.user.quickauthorizationapplicationcategory_set.all()
            category_list = [i.category for i in obj.quick_category.all()]
            category_json = []
            for tt in category_obj:
                flag1 = 'false'
                if tt.category in category_list:
                    flag1 = 'true'
                category_json.append({'id': tt.id, 'category': tt.category, 'flag': flag1})

            copy_obj = MakeCopy.objects.filter(type='a', process_id=int(id))
            copy_flag = 'ture' if copy_obj.count() else 'false'

            if obj.sealapplyauditrecord_set.filter(node="C/D"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="C/D"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["C/D"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="B"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="B"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["B"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                  'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="ys"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="ys"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["ys"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="BGS"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="BGS"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["BGS"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="sjk"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="sjk"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["sjk"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="stb"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="stb"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["stb"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YB"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YB"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YB"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YZ"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YZ"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YZ"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="audits"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="audits"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["audits"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}


            if obj.sealapplyauditrecord_set.filter(node="END_2"):
                print("有这个流程！")
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END_2"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END_2"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            data_dic = {'obj': obj, 'audit_dic': audit_dic, 'realname': request.user.real_name,
                        'position': request.user.post, 'department': obj.apply_user.department,
                        'main_file_list': main_file_list,
                        'is_edit': 'true' if obj.state == 'six' and obj.apply_user == request.user else 'false',
                        'quick_category': ', '.join([i.category for i in obj.quick_category.all()]),
                        'category_json': category_json, 'Quick': 'false',
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'seven', 'eight', 'nine', 'thirteen'] and request.user in obj.current_audit_users.all() else 'false',
                        'is_voucher': 'true' if BGS_appave == request.user and obj.voucher == '0' else 'false',
                        'leaders_obj': leaders_obj, 'Bstep': Bstep, 'sjk_obj': sjk_obj,
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine', 'thirteen'] and request.user == obj.apply_user else 'false',
                        'user_obj': User.objects.filter(group_id=1), 'dzb_obj': dzb_obj, 'print_flag': 'true' if (request.user in end_list) and obj.state == 'five' else 'flase',
                        'uuid': obj.fj_number, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(
                    topics_number=obj.fj_number) else "", 'user_type': user_type, 'state': obj.state, 'flow_dict': flow_dict, "seal_obj": seal_obj, "flag": flag, "copy_obj": copy_obj, "copy_flag": copy_flag}
            return render(request, "personal_center/seal_detail_page_old.html", data_dic)

    def post(self, request):
        id = request.POST.get('id', None)
        leader_id = request.POST.get('leader_id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        cs_people = request.POST.get("cs_people", None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "用印审批")
        except:
            pass
        obj = SealApply.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        remaining_flag = False
        if obj.state == 'one':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='C/D', state='unaudit').first()
            if obj.is_fast:
                if obj.authorization_type == '1':               # 法人授权
                    if obj.leval == '1':
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        if state == 'audit':
                            obj_state = 'two'
                            obj.current_audit_users.add(next_audit_record.audit_people)
                        else:
                            obj_state = 'six'
                            obj.current_audit_users.add(obj.apply_user)
                    else:
                        TwoSeptObj = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        TwoSeptObj.update_time = datetime.now()
                        TwoSeptObj.state = 'audit'
                        TwoSeptObj.save()

                        ThreeSeptObj = obj.sealapplyauditrecord_set.filter(node='ys', state='unaudit').first()
                        ThreeSeptObj.update_time = datetime.now()
                        ThreeSeptObj.state = 'audit'
                        ThreeSeptObj.save()

                        if obj.sealapplyauditrecord_set.filter(node='sjk'):
                            next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
                            obj_state = 'nine'
                        else:
                            next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                            obj_state = 'four'

                        if state == 'audit':
                            obj.current_audit_users.add(next_audit_record.audit_people)
                        else:
                            obj_state = 'six'
                            obj.current_audit_users.add(obj.apply_user)
                        MakeCopy.objects.create(recipient=TwoSeptObj.audit_people, process_id=obj.id, type='a')
                        MakeCopy.objects.create(recipient=ThreeSeptObj.audit_people, process_id=obj.id, type='a')

                else:                                           # 分管授权
                    TwoSeptObj = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                    TwoSeptObj.update_time = datetime.now()
                    TwoSeptObj.state = 'audit'
                    TwoSeptObj.save()

                    MakeCopy.objects.create(recipient=TwoSeptObj.audit_people, process_id=obj.id, type='a')

                    if obj.sealapplyauditrecord_set.filter(node='sjk'):
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                        obj_state = 'four'

                    if state == 'audit':
                        obj.current_audit_users.add(next_audit_record.audit_people)
                    else:
                        obj_state = 'six'
                        obj.current_audit_users.add(obj.apply_user)

            else:
                if state == 'audit':
                    if obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').count():
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        obj_state = 'two'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                        obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
            if state == 'audit':
                if obj.is_fast:
                    ThreeSeptObj = obj.sealapplyauditrecord_set.filter(node='ys', state='unaudit').first()
                    ThreeSeptObj.update_time = datetime.now()
                    ThreeSeptObj.state = 'audit'
                    ThreeSeptObj.save()
                    MakeCopy.objects.create(recipient=ThreeSeptObj.audit_people, process_id=obj.id, type='a')

                    if obj.FileType == "1":
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit')
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                        obj_state = 'four'
                else:
                    if obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit'):
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit')
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                        obj_state = 'four'

                for cur in next_audit_record:
                    obj.current_audit_users.add(cur.audit_people)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='YB', state='unaudit').first()
            if state == 'audit':
                dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                sq_list = obj.seal_name.split(', ')
                dw_flag, yb_flag = False, False
                for sq1 in sq_list:
                    if sq1 in dw_list:
                        dw_flag = True
                    if sq1 in yb_list:
                        yb_flag = True
                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                    obj.current_audit_users.add(BGS_appave)
                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                    obj.current_audit_users.add(BGS_appave)

                obj_state = 'eight'
            elif state == "referral":
                for LEADER in leader_id.split(","):
                    leader_obj = User.objects.get(id=int(LEADER))
                    SealApplyAuditRecord.objects.create(node='YZ', state='unaudit', audit_people=leader_obj, parent_id=obj)
                    obj.current_audit_users.add(leader_obj)
                obj_state = 'seven'
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            if obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user):
                obj.current_audit_users.remove(request.user)
                audit_record = ""
                audit_step = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                for aud_four in audit_step:
                    if aud_four.audit_people == request.user:
                        audit_record = aud_four
                if state == 'audit':
                    if audit_step.count() == 1:
                        obj_state = 'thirteen'

                        number_list = re.findall('\((.*?)\)', cs_people)
                        dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                        yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                        sq_list = obj.seal_name.split(', ')
                        number_list.append(Company.objects.get(id=3).head_people.job_number)
                        number_list = list(set(number_list))
                        for i in number_list:
                            MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)

                        bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                        for bgs_people in bgs_obj:
                            SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit', audit_people=bgs_people.audit_people, parent_id=obj)
                            obj.current_audit_users.add(bgs_people.audit_people)
                    else:
                        obj_state = 'four'
                        remaining_flag = True
                elif state == "referral":
                    obj.current_audit_users.clear()
                    dz_obj = Company.objects.get(id=3).head_people
                    YbObj = Company.objects.get(id=80).head_people
                    sjk_obj = Company.objects.get(id=22).head_people
                    leader_obj = User.objects.get(id=leader_id)
                    if leader_obj == dz_obj or leader_obj == YbObj:
                        crrt_node = 'YB'
                        obj_state = 'three'
                    elif leader_obj == sjk_obj:
                        crrt_node = 'sjk'
                        obj_state = 'nine'
                    else:
                        crrt_node = 'YZ'
                        obj_state = 'seven'
                    SealApplyAuditRecord.objects.create(node=crrt_node, state='unaudit', audit_people=leader_obj, parent_id=obj)
                    obj.current_audit_users.add(leader_obj)
                    for aud_four1 in audit_step:
                        if aud_four1.audit_people != request.user:
                            aud_four1.delete()
                else:
                    obj_state = 'six'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
            else:
                try:
                    audit_record = obj.sealapplyauditrecord_set.filter(audit_people=request.user).first()
                    if state == 'audit':
                        obj_state = 'four'
                    else:
                        obj_state = 'six'
                        obj.current_audit_users.clear()
                        obj.current_audit_users.add(obj.apply_user)
                except:
                    returnData = {'code': 200, 'message': '审核成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

        elif obj.state == 'five':
            returnData = {'code': 200, 'message': '上传成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        elif obj.state == 'seven':
            obj.current_audit_users.remove(request.user)
            audit_record = obj.sealapplyauditrecord_set.filter(node='YZ', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = "seven"
                else:
                    obj_state = 'eight'
                    dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                    sq_list = obj.seal_name.split(', ')
                    dw_flag, yb_flag = False, False
                    for sq1 in sq_list:
                        if sq1 in dw_list:
                            dw_flag = True
                        if sq1 in yb_list:
                            yb_flag = True
                    if yb_flag:
                        BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                        SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                        obj.current_audit_users.add(BGS_appave)
                    if dw_flag:
                        BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                        SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave, parent_id=obj)
                        obj.current_audit_users.add(BGS_appave)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'eight' or obj.state == 'twelve':
            audit_record = ""
            obj.current_audit_users.remove(request.user)
            if obj.state == 'eight':
                audit_step = obj.sealapplyauditrecord_set.filter(node='END', state='unaudit')
            else:
                audit_step = obj.sealapplyauditrecord_set.filter(node='END_2', state='unaudit')
            for foue in audit_step:
                if foue.audit_people == request.user:
                    audit_record = foue
            if state == 'audit':
                if audit_step.count() == 1:
                    obj_state = 'thirteen'

                    number_list = re.findall('\((.*?)\)', cs_people)
                    # dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    # yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                    # sq_list = obj.seal_name.split(', ')
                    number_list.append(Company.objects.get(id=3).head_people.job_number)
                    number_list = list(set(number_list))
                    for i in number_list:
                        MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)
                    bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                    for bgs_people in bgs_obj:
                        SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit', audit_people=bgs_people.audit_people, parent_id=obj)
                        obj.current_audit_users.add(bgs_people.audit_people)
                else:
                    obj_state = 'eight'
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine' or obj.state == 'eleven':
            obj.current_audit_users.clear()
            if obj.state == 'nine':
                audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
            else:
                audit_record = obj.sealapplyauditrecord_set.filter(node='audits', state='unaudit').first()

            if state == 'audit':
                if obj.state == 'nine':
                    next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                    obj_state = 'four'
                else:
                    next_audit_record = obj.sealapplyauditrecord_set.filter(node='END_2', state='unaudit')
                    obj_state = 'twelve'
                for cur in next_audit_record:
                    obj.current_audit_users.add(cur.audit_people)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'ten':
            obj.current_audit_users.remove(request.user)
            audit_record = ""
            audit_step = obj.sealapplyauditrecord_set.filter(node='stb', state='unaudit')
            for aud_four in audit_step:
                if aud_four.audit_people == request.user:
                    audit_record = aud_four
            if state == 'audit':
                if audit_step.count() == 1:
                    obj_state = 'thirteen'

                    number_list = re.findall('\((.*?)\)', cs_people)
                    # dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    # yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                    # sq_list = obj.seal_name.split(', ')
                    number_list.append(Company.objects.get(id=3).head_people.job_number)
                    number_list = list(set(number_list))
                    for i in number_list:
                        MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)
                    bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                    for bgs_people in bgs_obj:
                        SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit', audit_people=bgs_people.audit_people, parent_id=obj)
                        obj.current_audit_users.add(bgs_people.audit_people)
                else:
                    obj_state = 'ten'
            elif state == "referral":
                obj.current_audit_users.clear()
                dz_obj = Company.objects.get(id=3).head_people
                leader_obj = User.objects.get(id=leader_id)
                if leader_obj == dz_obj:
                    crrt_node = 'YB'
                    obj_state = 'three'
                else:
                    crrt_node = 'YZ'
                    obj_state = 'seven'
                SealApplyAuditRecord.objects.create(node=crrt_node, state='unaudit', audit_people=leader_obj, parent_id=obj)
                obj.current_audit_users.add(leader_obj)
                for aud_four1 in audit_step:
                    if aud_four1.audit_people != request.user:
                        aud_four1.delete()
            else:
                obj_state = 'six'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'thirteen':
            obj.current_audit_users.remove(request.user)
            audit_record = obj.sealapplyauditrecord_set.filter(node='thirteen', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    obj_state = 'five'
                    TimeNode = datetime.now().strftime('%Y%m')
                    try:
                        seal_obj = SealApplyNumber.objects.get(time_node=TimeNode)
                        current_number = seal_obj.current_number
                        next_number = seal_obj.next_number
                        seal_obj.current_number = int(current_number) + 1
                        seal_obj.next_number = int(next_number) + 1
                        seal_obj.save()
                    except:
                        current_number = 0  # 当前编号
                        next_number = 1  # 下一个编号（取这个值）
                        SealApplyNumber.objects.create(current_number=current_number + 1, next_number=next_number + 1, time_node=TimeNode)

                    current_date = datetime.now().strftime('%Y-%m-%d')
                    current_date_str = current_date.replace('-', '')

                    next_number = "0" + str(next_number) if int(next_number) < 10 else str(next_number)
                    number = 'JYYZ-' + str(current_date_str) + '-' + next_number
                    obj.number = number
                else:
                    obj_state = 'thirteen'
            else:
                obj_state = 'six'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        if remaining_flag and not obj.current_audit_users.all().count():
            remaining_obj = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
            for remaining in remaining_obj:
                obj.current_audit_users.add(remaining.audit_people)
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "用印审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.matter_type_text[:15] + "……" if len(obj.matter_type_text) > 15 else obj.matter_type_text
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SealApplyWriteView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        servings = request.POST.get('servings', 1)
        seal_name = request.POST.get('seal_name', None)
        credentials = request.POST.get('credentials', None)
        matter_type_text = request.POST.get('matter_type_text', None)
        fj_number = request.POST.get('fj_number', None)
        note = request.POST.get('note', '')
        YDetail = request.POST.get('YDetail', '')
        leader_select = request.POST.get('leader_select', None)  # 分管领导
        FileType = request.POST.get('FileType', '')
        b_step = User.objects.get(id=int(leader_select))
        QuickApplication = False
        quick_obj = request.user.company.quickauthorizationseal_set.all()
        if quick_obj.count():
            if matter_type_text == "其他":
                matter_type_text = YDetail
            else:
                QuickApplication = True

        obj = SealApply.objects.get(id=int(id))
        obj.is_fast = QuickApplication
        obj.seal_name = seal_name
        obj.note = note
        obj.FileType = FileType
        obj.matter_type_text = matter_type_text
        obj.fg_id = leader_select
        obj.credentials = credentials if credentials != 'undefined' else ''
        obj.fj_number = fj_number
        obj.servings = int(servings)
        obj.save()

        obj.sealapplyauditrecord_set.filter(state='unaudit').delete()
        obj.current_audit_users.clear()

        dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
        yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']

        one_appave = user.company.head_people

        sq_list = seal_name.split(', ')
        dw_flag, yb_flag = False, False
        for sq1 in sq_list:
            if sq1 in dw_list:
                dw_flag = True
            if sq1 in yb_list:
                yb_flag = True
        if QuickApplication:
            if one_appave != user:
                SealApplyAuditRecord.objects.create(node='C/D', state='audit', audit_people=one_appave, parent_id=obj)
                obj.audit_users_already.add(one_appave)

            if quick_obj.first().authorization_level == "1":
                SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=b_step, parent_id=obj)
                obj.current_audit_users.add(b_step)
                SealApplyAuditRecord.objects.create(node='ys', state='unaudit', audit_people=Staffing.objects.get(
                    station='院长').post_personnel.all().first(), parent_id=obj)
                if FileType == "1":
                    sjk_obj = Company.objects.get(id=22).head_people
                    SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=sjk_obj,
                                                        parent_id=obj)
                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                obj.state = 'two'

            else:
                SealApplyAuditRecord.objects.create(node='B', state='audit', audit_people=b_step, parent_id=obj)
                obj.audit_users_already.add(b_step)
                SealApplyAuditRecord.objects.create(node='ys', state='audit', audit_people=Staffing.objects.get(
                    station='院长').post_personnel.all().first(), parent_id=obj)
                obj.audit_users_already.add(Staffing.objects.get(station='院长').post_personnel.all().first())
                aaaa = True
                if FileType == "1":
                    sjk_obj = Company.objects.get(id=22).head_people
                    SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=sjk_obj,
                                                        parent_id=obj)
                    obj.current_audit_users.add(sjk_obj)
                    aaaa = False
                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                    if aaaa:
                        obj.current_audit_users.add(BGS_appave)
                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                    if aaaa:
                        obj.current_audit_users.add(BGS_appave)
                obj.state = 'four'

            obj.save()
        else:
            flag = True
            if one_appave != user:
                SealApplyAuditRecord.objects.create(node='C/D', state='unaudit', audit_people=one_appave, parent_id=obj)
                obj.current_audit_users.add(one_appave)
                obj.state = 'one'
                flag = False
            SealApplyAuditRecord.objects.create(node='B', state='unaudit', audit_people=b_step, parent_id=obj)
            if flag:
                obj.current_audit_users.add(b_step)
                obj.state = 'two'

            if FileType == "1":
                sjk_obj = Company.objects.get(id=22).head_people
                SealApplyAuditRecord.objects.create(node='sjk', state='unaudit', audit_people=sjk_obj, parent_id=obj)

            if yb_flag:
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)
            if dw_flag:
                BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                SealApplyAuditRecord.objects.create(node='BGS', state='unaudit', audit_people=BGS_appave, parent_id=obj)
            achments_objs = Topicsattachments.objects.filter(topics_number=obj.fj_number)

            for achments_obj in achments_objs:
                achments_obj.watch_users.add(obj.apply_user)
                for r in obj.sealapplyauditrecord_set.all():
                    if r.audit_people not in achments_obj.watch_users.all():
                        achments_obj.watch_users.add(r.audit_people)
            obj.save()
        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SealApplyRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = SealApply.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'six':
                returnData = {'code': 500, 'message': '作废失败，只有未审批完毕的用印申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.sealapplyauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的用印申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'five':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的用印申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class summary_page(View):
    def post(self, request):
        tic_type = request.POST.get("tic_type", None)
        will_or_not = request.POST.get("meet_num", None)
        page = request.POST.get("page", None)
        all_data = Topics.objects.filter(meetings_num=will_or_not, type=tic_type, state__in=["done", "metting"])
        relust_list = []
        for i in all_data:
            one_dict = {'id': i.id, "name": i.topics_name, "number": i.number, "dep": i.employee.department,
                        'tjr': i.employee.real_name, 'tjsj': str(i.create_time).split('.')[0][:-3],
                        'spsj': i.topicsauditrecord_set.filter(node='YB/DB').last().update_time,
                        'meeting_num': i.meetings_num, 'is_yb': 1 if i.is_yb else 0,
                        "relust": 1 if i.topicsauditrecord_set.filter(node='result') else 0}

            relust_list.append(one_dict)

        relust_list.sort(key=itemgetter('spsj'), reverse=False)
        shangdict = {}
        for t in relust_list:
            if t["dep"] in shangdict:
                shangdict[t["dep"]].append(t)
            else:
                shangdict[t["dep"]] = [t]
        YbShangList = []
        for j in shangdict:
            for k in shangdict[j]:
                tttt = str(k["spsj"]).split(".")[0][:-3]
                k["spsj"] = tttt
                YbShangList.append(k)

        returnDict = {'code': 200, 'message': '', "data": YbShangList[(int(page) - 1) * 30:int(page) * 30],
                      "data_len": len(YbShangList)}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class topic_discussion(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        topic_type = request.GET.get("type", 'yb')

        year_data = Topics.objects.filter(state__in=["done", "metting"], type=topic_type)
        year_list = sorted(list(set([int(i.iss_year) for i in year_data if i.iss_year.strip()])))

        meet_type = "院长办公会" if topic_type == "yb" else "党委会" if topic_type == "db" else "行政例会"

        LeftDict = []
        for year in range(len(year_list)):
            one_dict = {}
            num_obj = Topics.objects.filter(state__in=["done", "metting"], type=topic_type, iss_year=year_list[year])
            NumberList = sorted(list(set([int(i.meetings_num) for i in num_obj])), reverse=True)
            meeting_name_list = []
            for j in NumberList:
                 meeting_name_list.append({"name": f"{year_list[year]}年第{j}次{meet_type}", "number": j, "year": year_list[year], "choose": 'flase'})

            keys = f"{year_list[year]}年{meet_type}"
            one_dict[keys] = meeting_name_list
            one_dict["open"] = 'false'
            LeftDict.append(one_dict)
        LeftDict[-1]["open"] = 'true'
        LeftDict[-1][list(LeftDict[-1].keys())[0]][0]["choose"] = 'true'

        choose_year = LeftDict[-1][list(LeftDict[-1].keys())[0]][0]["year"]
        choose_number = LeftDict[-1][list(LeftDict[-1].keys())[0]][0]["number"]
        fujian_uuid = uuid.uuid4()
        permissions_dict = GetGroupView("议题目录", request.user)
        for key, val in permissions_dict.items():
            if val:
                permissions_dict[key] = 'true'
            else:
                permissions_dict[key] = 'flase'
        return render(request, "personal_center/topic_discussion.html", {'realname': real_name, 'position': position, 'department': department, "returnData": [], "LeftDict": LeftDict, "choose_year": choose_year, "choose_number": choose_number, "topic_type": topic_type, "permissions": permissions_dict, "uuid": fujian_uuid})

    def post(self, request):
        id_list = request.POST.get("id_list", None)  # 临时上会id列表
        sh_type = request.POST.get("sh_type", False)  # 上会类型
        now_year = datetime.now().year
        meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year), is_meeting='b')
        max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list]) if [int(i.meetings_num) for i in meetings_num_list] else 0
        if max_meetings_num == 0:
            now_year = int(now_year) - 1
            meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year))
            max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list])

        # *********************************** 生成pdf文件 ****************************************
        file_name = ""
        pdf_file_list = []
        page_list = []
        for i in json.loads(id_list):
            one_dict = {}
            yiti_yb_obj = Topics.objects.get(id=int(i))

            yiti_yb_obj.meetings_num = max_meetings_num
            yiti_yb_obj.is_meeting = 'b'
            yiti_yb_obj.iss_yesr = now_year
            yiti_yb_obj.state = "metting"
            yiti_yb_obj.save()

            already_meet = topic_meeting.objects.filter(topic_type=yiti_yb_obj.type, meet_number=max_meetings_num, topic_year=yiti_yb_obj.iss_year).first()
            topic_meeting.objects.create(meet_number=max_meetings_num, topic_type=yiti_yb_obj.type, meet_time=already_meet.meet_time, topic_year=yiti_yb_obj.iss_year, topic=yiti_yb_obj)

            one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
            one_dict["title"] = yiti_yb_obj.topics_name
            one_dict["dep"] = yiti_yb_obj.employee.department
            one_dict["tjr"] = yiti_yb_obj.employee.real_name
            one_dict["ytbh"] = yiti_yb_obj.number
            one_dict["ygys"] = yiti_yb_obj.topics_estimate
            one_dict["nrwb"] = yiti_yb_obj.nrwb
            one_dict["zcyj"] = yiti_yb_obj.zcwb
            one_dict["fawb"] = yiti_yb_obj.fawb
            one_dict["ysje"] = yiti_yb_obj.ysje
            one_dict["jfly"] = yiti_yb_obj.jfly
            one_dict["nrwb_base"] = yiti_yb_obj.topics_text
            one_dict["fawb_base"] = yiti_yb_obj.solution
            one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
            audit_dic = {}
            for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': os.getcwd() + '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': os.getcwd() + '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            one_dict["audit_dic"] = audit_dic
            if sh_type == "yb":
                file_name = f'{now_year}年第{max_meetings_num}次院长办公会'
                file_path = directory().yb_func(one_dict, sh_type, file_name)
            elif sh_type == "db":
                file_name = f"{now_year}年第{max_meetings_num}次党委会"
                file_path = directory().db_func(one_dict, sh_type, file_name)
            else:
                file_name = f"{now_year}年第{max_meetings_num}次行政例会"
                file_path = directory().xz_func(one_dict, sh_type, file_name)

            pdf_file_list.append(file_path)
            text_page = get_num_pages(file_path)
            pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_yb_obj.uuid, file_type="0")
            for path in pdf_path_list:
                pdf_file_path = os.getcwd() + path.pdf_path
                if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                    if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                        pdf_file_list.append(pdf_file_path)
                        enclosure_page = get_num_pages(pdf_file_path)
                        text_page += enclosure_page
                    elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                        pdf_tp_path = image_to_pdf(pdf_file_path)
                        pdf_file_list.append(pdf_tp_path)
                        enclosure_page = get_num_pages(pdf_tp_path)
                        text_page += enclosure_page

            page_list.append(text_page)

        file_merger = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        for pdf in pdf_file_list:
            file_merger.append(pdf)  # 合并pdf文件
        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file/temp"
        if os.path.exists(Issue_information_path):
            shutil.rmtree(Issue_information_path)
            os.makedirs(Issue_information_path)
        else:
            os.makedirs(Issue_information_path)
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料1.pdf"  # PDF 议题资料路径
        if os.path.exists(pdf_path):
            os.remove(pdf_path)
        file_merger.write(pdf_path)

        old_file_path = os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料.pdf"
        reader = PdfFileReader(old_file_path)
        page_num = reader.getNumPages()

        shutil.move(os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料.pdf", Issue_information_path)
        file_merger1 = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        all_pdf_list = [os.getcwd() + f"/media/Issue_information/pdf_file/temp/{file_name}-会议资料.pdf", pdf_path]
        for pdf1 in all_pdf_list:
            file_merger1.append(pdf1)  # 合并pdf文件
        if os.path.exists(os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料1.pdf"):
            os.remove(os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料1.pdf")

        pdf_path1 = os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料1.pdf"  # PDF 议题资料路径
        file_merger1.write(pdf_path1)

        os.rename(pdf_path1, os.getcwd() + f"/media/Issue_information/pdf_file/{file_name}-会议资料.pdf")

        # *********************************** 生成excel文件 ****************************************
        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict = [], [], [], {}, {}, {}
        id_list = json.loads(id_list)
        if sh_type == 'yb':
            Yb_AllList = []
            for i in range(len(id_list)):
                Ybobj = Topics.objects.get(id=int(id_list[i]))
                Yb_AllList.append(["", Ybobj.topics_name, Ybobj.employee.department, Ybobj.employee.real_name,
                           str(Ybobj.create_time).split(".")[0][:-3],
                           str(Ybobj.topicsauditrecord_set.all().order_by('update_time').last().update_time).split(".")[0][:-3],
                           Ybobj.employee.company.leaders])

            for ij in range(len(Yb_AllList)):
                start_page = int(page_num) + 1
                end_page = int(page_num) + 1 + (int(page_list[ij]) - 1)
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Yb_AllList[ij].append(page_number)
                YbAllList.append(Yb_AllList[ij])
                page_num = end_page

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/yb"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            workbook = xlrd.open_workbook(file_path + f"/{file_name}-会议目录.xlsx")
            table_stjgb = workbook.sheet_by_index(0)
            old_data_list = []
            for i in range(2, table_stjgb.nrows):  # 遍历每一行
                old_data_list.append(table_stjgb.row_values(i))
            create_table().excel_append(old_data_list + YbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)

        elif sh_type == 'db':
            id_list = []
            for ids in Topics.objects.filter(iss_yesr=now_year, meetings_num=max_meetings_num, type='db'):
                id_list.append(ids.id)
            YbZhuanDbAllList, YbZhuanDbAllDict, YbDbAllDict, Db_AllList, Db_zh_alllidt, Db_all_list, Yb_ZhuanDbAllList = [], {}, {}, [], [], [], []
            for i in range(len(id_list)):
                Dbobj = Topics.objects.get(id=int(id_list[i]))
                db_dict = [Dbobj.topics_name, Dbobj.employee.department, Dbobj.employee.real_name,
                           str(Dbobj.create_time).split(".")[0][:-3], str(Dbobj.update_time).split(".")[0][:-3],
                           Dbobj.employee.company.director if Dbobj.employee.company.director else Dbobj.employee.company.deputy_director,
                           Dbobj.id]
                if Dbobj.is_yb:
                    if Dbobj.employee.department in YbZhuanDbAllDict:
                        YbZhuanDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbZhuanDbAllDict[Dbobj.employee.department] = [db_dict]

                else:
                    if Dbobj.employee.department in YbDbAllDict:
                        YbDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbDbAllDict[Dbobj.employee.department] = [db_dict]

            for Tj in YbZhuanDbAllDict:
                Db_zh_alllidt += YbZhuanDbAllDict[Tj]
            for TT in range(len(Db_zh_alllidt)):
                Db_zh_alllidt[TT].insert(0, TT + 1)
                new_list = Db_zh_alllidt[TT][:2]
                new_list.append(Db_zh_alllidt[TT][-1])
                YbZhuanDbAllList.append(new_list)

            for ij in range(len(YbZhuanDbAllList)):
                start_page = sum(page_list[:ij]) + 1
                end_page = sum(page_list[:ij + 1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                YbZhuanDbAllList[ij].append(page_number)
                Yb_ZhuanDbAllList.append(YbZhuanDbAllList[ij])

            for JJ in YbDbAllDict:
                Db_all_list += YbDbAllDict[JJ]
            for TJ in range(len(Db_all_list)):
                Db_all_list[TJ].insert(0, TJ + 1)
                Db_AllList.append(Db_all_list[TJ])

            page_start = len(YbZhuanDbAllList)
            for ij in range(len(Db_AllList)):
                start_page = sum(page_list[:page_start]) + 1
                end_page = sum(page_list[:page_start + 1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Db_AllList[ij].append(page_number)
                DbAllList.append(Db_AllList[ij])
                page_start += 1
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/db"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            create_table().db_excel(Yb_ZhuanDbAllList, DbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)

        else:
            id_list = []
            for ids in Topics.objects.filter(iss_yesr=now_year, meetings_num=max_meetings_num, type='xz'):
                id_list.append(ids.id)
            Xz_AllList = []
            for i in range(len(id_list)):
                Xzobj = Topics.objects.get(id=int(id_list[i]))
                lh_dict = [Xzobj.topics_name, Xzobj.employee.department, Xzobj.employee.real_name,
                           str(Xzobj.create_time).split(".")[0][:-3],
                           str(Xzobj.update_time).split(".")[0][:-3], Xzobj.employee.company.leaders, Xzobj.id]
                if Xzobj.employee.department in LhDict:
                    LhDict[Xzobj.employee.department].append(lh_dict)
                else:
                    LhDict[Xzobj.employee.department] = [lh_dict]
            Lh_AllList = []
            for IY in LhDict:
                Lh_AllList += LhDict[IY]

            for Yi in range(len(Lh_AllList)):
                Lh_AllList[Yi].insert(0, Yi + 1)
                XzAllList.append(Lh_AllList[Yi])

            for IJ in range(len(XzAllList)):
                start_page = sum(page_list[:IJ]) + 1
                end_page = sum(page_list[:IJ + 1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                XzAllList[IJ].append(page_number)
                Xz_AllList.append(XzAllList[IJ])

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/xz"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            create_table().yb_excel(Xz_AllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
        returnDict = {'code': 200, 'message': ''}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class pass_yb(View):
    def post(self, request):
        tic_id = request.POST.get("tic_id", None)
        is_yb = request.POST.get("is_yb", False)
        if is_yb.strip():
            is_yb = True
        else:
            is_yb = False
        tic_obj = Topics.objects.get(id=int(tic_id))
        tic_obj.is_yb = is_yb
        tic_obj.save()
        returnDict = {'code': 200, 'message': '修改成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PublicSearchView(View):
    def get(self, request):
        search_key = request.GET.get('search_key', None)
        page = request.GET.get('page', 1)
        user = request.user
        my_apply_objs = user.publicsearch_set.filter(content__contains=search_key)
        my_audit_objs = user.public_search_users.filter(content__contains=search_key)
        my_already_audit_objs = user.public_search_already_audit_users.filter(content__contains=search_key)
        my_apply_list = [{'type': record.get_type_display(), 'state': record.state,
                          'audit_user': ', '.join([i.real_name for i in record.current_audit_users.all()]),
                          'content': record.content} for record
                         in my_apply_objs[(int(page) - 1) * 20:int(page) * 20]]
        my_audit_list = [{'type': record.get_type_display(), 'state': record.state,
                          'audit_user': ', '.join([i.real_name for i in record.current_audit_users.all()]),
                          'content': record.content} for record
                         in my_audit_objs[(int(page) - 1) * 20:int(page) * 20]]
        my_already_audit_list = [{'type': record.get_type_display(), 'state': record.state,
                                  'audit_user': ', '.join([i.real_name for i in record.current_audit_users.all()]),
                                  'content': record.content} for
                                 record
                                 in my_already_audit_objs[(int(page) - 1) * 20:int(page) * 20]]
        returnDict = {'code': 200, 'message': '获取成功', 'my_apply_list': my_apply_list, 'my_audit_list': my_audit_list,
                      'my_already_audit_list': my_already_audit_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class dayin_pdf(View):
    def post(self, request):
        tic_id = request.POST.get("id", None)
        iss_type = request.POST.get("iss_type", None)
        one_dict = {}
        yiti_yb_obj = Topics.objects.get(id=int(tic_id))
        one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
        one_dict["title"] = yiti_yb_obj.topics_name
        one_dict["dep"] = yiti_yb_obj.employee.department
        one_dict["tjr"] = yiti_yb_obj.employee.real_name
        one_dict["ytbh"] = yiti_yb_obj.number
        one_dict["ygys"] = yiti_yb_obj.topics_estimate
        one_dict["nrwb"] = yiti_yb_obj.nrwb
        one_dict["zcyj"] = yiti_yb_obj.zcwb
        one_dict["fawb"] = yiti_yb_obj.fawb
        one_dict["ysje"] = yiti_yb_obj.ysje
        one_dict["jfly"] = yiti_yb_obj.jfly
        one_dict["nrwb_base"] = yiti_yb_obj.topics_text
        one_dict["fawb_base"] = yiti_yb_obj.solution
        one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
        audit_dic = {}
        for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': os.getcwd() + '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.get_state_display(),
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': os.getcwd() + '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        one_dict["audit_dic"] = audit_dic
        if iss_type == "yb":
            file_path = directory().yb_func(one_dict, iss_type, str(int(time.time())), dowload=True)
        elif iss_type == "db":
            file_path = directory().db_func(one_dict, iss_type, str(int(time.time())), dowload=True)
        else:
            file_path = directory().xz_func(one_dict, iss_type, str(int(time.time())), dowload=True)

        returnDict = {'code': 200, 'message': '修改成功', "data": [{"file_path": file_path.replace(os.getcwd(), "")}]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class document_dayin(View):
    def post(self, request):
        tic_id = request.POST.get("id", None)
        iss_type = request.POST.get("iss_type", None)
        try:
            conference_memo_obj = ConferenceMemo.objects.get(id=tic_id)

        except Exception as e:
            returnDict = {'code': 500, 'message': '获取错误！请联系管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic = {}
            for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            data_dic = {
                'id': conference_memo_obj.id,
                'state': conference_memo_obj.get_state_display(),
                'apply_user': conference_memo_obj.drafter if conference_memo_obj.drafter else conference_memo_obj.apply_user.real_name,
                'department': conference_memo_obj.drafter_company if conference_memo_obj.drafter_company else conference_memo_obj.apply_user.department,
                'drafter': conference_memo_obj.drafter,
                'drafter_company': conference_memo_obj.drafter_company,
                'servings': conference_memo_obj.servings,
                'type': conference_memo_obj.type,
                'conference_memo_text': conference_memo_obj.conference_memo_text,
                'main_company': conference_memo_obj.main_company,
                'vice_company': conference_memo_obj.vice_company,
                'document_number': conference_memo_obj.document_number,
                'number': conference_memo_obj.number,
                'audit_list': audit_dic
            }

        if iss_type == "yb":
            file_path = document_pdf().create_pdf(data_dic, iss_type)
        elif iss_type == "db":
            file_path = document_pdf().create_pdf(data_dic, iss_type)
        else:
            file_path = document_pdf().create_pdf(data_dic, iss_type)
        # file_path = ""

        returnDict = {'code': 200, 'message': '修改成功', "data": [{"file_path": file_path.replace(os.getcwd(), "")}]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class Privacy_Policy(View):
    def get(self, request):
        return render(request, "personal_center/Privacy_Policy.html")


class ask_preview(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = OfficialDocuments.objects.get(id=int(id.replace("#", '')))
        audit_dic = {}

        for audit_obj in obj.officialdocumentsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': os.getcwd() + '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.get_state_display(),
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': os.getcwd() + '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        recive_people = [{'user': record.audit_people.real_name, 'state': record.get_state_display(),
                          'signature_picture': os.getcwd() + '/media/' + str(
                              record.audit_people.signature_picture) if (
                                  record.audit_people.signature_picture and record.state == 'accepted') else '',
                          'update_time': record.update_time.strftime(
                              "%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                         for record in obj.officialdocumentspeople_set.all()]

        data_dic = {
            'id': obj.id,
            'node': obj.get_type_display(),
            'type': obj.state,
            'apply_user': obj.apply_user.real_name,
            'department': obj.apply_user.department,
            'send_number': obj.send_number,
            'recive_number': obj.recive_number,
            'title': obj.title,
            'send_company': obj.send_company,
            'content': obj.content,
            'annotated_text': obj.annotated_text,
            'time_limit': obj.time_limit,
            'audit_dic': audit_dic,
            'recive_people': recive_people,
            'recive_time': obj.recive_time.strftime("%Y-%m-%d %H:%M"),
            'remarks': obj.remarks
        }
        pdf_path = Jeremy_levin_preview().levin_preview(data_dic)
        returnDict = {'code': 200, 'message': '修改成功', "data": [{"file_path": pdf_path.replace(os.getcwd(), "")}]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class RecordManagement(View):
    def get(self, request):
        """我的收文"""
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")

        select_sql = f"""
            SELECT types, SUM(num) FROM 
            (SELECT b.type types, COUNT(b.type) num FROM (SELECT * FROM administrative_conferencememopeople WHERE state='accepted' AND audit_people_id={request.user.id}) a LEFT JOIN administrative_conferencememo b ON a.notice_id_id=b.id GROUP BY b.type	
            UNION ALL
            SELECT 'a' types, 0 num 
            UNION ALL
            SELECT 'b' types, 0 num
            UNION ALL
            SELECT 'c' types, 0 num
            UNION ALL
            SELECT 'd' types, 0 num
            UNION ALL
            SELECT 'e' types, 0 num
            UNION ALL
            SELECT 'f' types, 0 num
            UNION ALL
            SELECT 'g' types, 0 num
            UNION ALL
            SELECT 'h' types, 0 num
            UNION ALL
            SELECT 'z' types, COUNT(*) num FROM administrative_officialdocumentspeople WHERE  state='accepted' AND audit_people_id={request.user.id}
            UNION ALL
            SELECT 'w' types, COUNT(*) num FROM administrative_correspondencepeople WHERE  state='accepted' AND audit_people_id={request.user.id}
            UNION ALL
            SELECT 'y' types, COUNT(*) num FROM supervision_inspection_committeeminutespeople WHERE  state='accepted' AND audit_people_id={request.user.id}
            ) base GROUP BY types ORDER BY types ASC
        """
        with connection.cursor() as cursor:
            cursor.execute(select_sql)
        all_data = cursor.fetchall()
        one_dict = {}
        for i in all_data:
            one_dict[i[0]] = i[1]

        select_sql1 = f"""
                    SELECT types, SUM(num) FROM 
                    (SELECT b.type types, COUNT(b.type) num FROM (SELECT * FROM administrative_conferencememopeople WHERE state='accept' AND audit_people_id={request.user.id}) a LEFT JOIN administrative_conferencememo b ON a.notice_id_id=b.id GROUP BY b.type	
                    UNION ALL
                    SELECT 'a' types, 0 num 
                    UNION ALL
                    SELECT 'b' types, 0 num
                    UNION ALL
                    SELECT 'c' types, 0 num
                    UNION ALL
                    SELECT 'd' types, 0 num
                    UNION ALL
                    SELECT 'e' types, 0 num
                    UNION ALL
                    SELECT 'f' types, 0 num
                    UNION ALL
                    SELECT 'g' types, 0 num
                    UNION ALL
                    SELECT 'h' types, 0 num
                    UNION ALL
                    SELECT 'z' types, COUNT(*) num FROM administrative_officialdocumentspeople WHERE  state='accept' AND audit_people_id={request.user.id}
                    UNION ALL
                    SELECT 'w' types, COUNT(*) num FROM administrative_correspondencepeople WHERE  state='accept' AND audit_people_id={request.user.id}
                    UNION ALL
                    SELECT 'y' types, COUNT(*) num FROM supervision_inspection_committeeminutespeople WHERE  state='accept' AND audit_people_id={request.user.id}
                    ) base GROUP BY types ORDER BY types ASC
                """
        with connection.cursor() as cursor:
            cursor.execute(select_sql1)
        all_data1 = cursor.fetchall()
        one_dict1 = {}
        for j in all_data1:
            one_dict1[j[0]] = j[1]
        return render(request, "personal_center/record_management.html",
                      {'realname': real_name, 'position': position, 'department': department, "one_dict": one_dict, "one_dict1": one_dict1})


class getBlogList(LoginRequiredMixin, View):
    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        datavalue = request.POST.get("datavalue", '')
        types = request.POST.get("types", "待收公文")
        if types == "已收公文":
            totals_number, data_list = my_shouwen().my_yishou(datavalue, search_data, request, page, page_size)
        else:
            totals_number, data_list = my_shouwen().my_daishou(datavalue, search_data, request, page, page_size)
        returnDict = {'status': 'success', "totals": totals_number, "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class chat_frame(View):
    """聊天界面"""
    def get(self, request):
        token = request.COOKIES.get("token", None)
        head_portrait = "/media/" + str(request.user.head_portrait)
        if head_portrait == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait):
            head_portrait = "/static/personal_center/img/头像.png"

        stu_list = list(User.objects.filter(is_superuser=0, is_delete=0).values("real_name", "head_portrait", "job_number"))
        all_dict = {}
        for i in stu_list:
            initial = hanzi_to_pinyin(i["real_name"])
            head_portrait1 = "/media/" + str(i["head_portrait"])
            if head_portrait1 == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait1):
                head_portrait1 = "/static/personal_center/img/头像.png"
            if "曾" == i["real_name"][0]:
                initial = "Z"
            if initial in all_dict:
                all_dict[initial].append({"name": i["real_name"], "picture": head_portrait1, "job_number": i["job_number"]})
            else:
                all_dict[initial] = [{"name": i["real_name"], "picture": head_portrait1, "job_number": i["job_number"]}]
        friend_list = {}
        for i in sorted(all_dict):
            friend_list[i] = all_dict[i]

        chattin_obj = chatting_records.objects.filter(Q(from_user=request.user) | Q(to_user=request.user)).order_by("-id").first()
        data_list = []
        if chattin_obj:
            if chattin_obj.from_user == request.user:
                room_name = chattin_obj.to_user.job_number
            elif chattin_obj.to_user == request.user:
                room_name = chattin_obj.from_user.job_number
            else:
                room_name = ""
        else:
            room_name = request.user.job_number

        # 消息， 时间
        all_list = chatting_records.objects.filter(Q(from_user=request.user) | Q(to_user=request.user)).order_by("-id")
        duplicate_removal = []
        for tt in all_list:
            one_list = [tt.from_user.id, tt.to_user.id]
            one_list.sort()
            if one_list not in duplicate_removal:
                duplicate_removal.append(one_list)

        group_list = ChatGroups.objects.filter(group_user=request.user)
        group_obj = []
        for group in group_list:
            group_obj.append({"group_name": group.group_name, 'roomName': group.room_id})

        chat_people_list = []
        for jj in duplicate_removal:
            chat_obj = chatting_records.objects.filter(Q(from_user=User.objects.get(id=jj[0]), to_user=User.objects.get(id=jj[1])) | Q(from_user=User.objects.get(id=jj[1]), to_user=User.objects.get(id=jj[0]))).order_by("-id").first()
            if chat_obj.from_user == request.user:
                chat_people = chat_obj.to_user
            else:
                chat_people = chat_obj.from_user
            head_sculpture = "/media/" + str(chat_people.head_portrait)
            if head_sculpture == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_sculpture):
                head_sculpture = "/static/personal_center/img/头像.png"

            chat_people_list.append({"job_number": chat_people.job_number, "real_name": chat_people.real_name, "head_sculpture": head_sculpture,
                                     "chat_time": "/".join(chat_obj.create_time.strftime("%Y-%m-%d %H:%M").split(" ")[0].split("-")[1:]), "message": json.loads(chat_obj.content)[0]["message"]})
        return render(request, "personal_center/chat_frame.html", {"head_portrait": head_portrait, "friend_list": friend_list, 'from_people': request.user.job_number, "real_name": request.user.real_name, "data_list": data_list,
                                                                   "room_name": room_name, "chat_people_list": chat_people_list, 'token': token, 'group_obj': group_obj})

    def post(self, request):
        content = request.POST.get('content', None)  # 聊天信息
        from_people = request.POST.get('from_people', None)  # 发信人
        roomName = request.POST.get('roomName', None)  # 收信人
        room_list = [int(from_people), int(roomName)]
        room_list.sort()
        room_str = str(room_list[0]) + str(room_list[1])
        room_id = hashlib.md5(room_str.encode(encoding='UTF-8')).hexdigest()
        content_dict = {"Sender": from_people, "content": content, "data": datetime.now().strftime("%Y-%m-%d %H:%M")}
        content_dict["to_name"] = User.objects.get(job_number=roomName).real_name
        content_dict["from_name"] = User.objects.get(job_number=from_people).real_name
        from_img = str(User.objects.get(job_number=from_people).head_portrait)
        content_dict["from_img"] = "/media/" + from_img if from_img else "/static/personal_center/img/头像.png"
        to_img = str(User.objects.get(job_number=roomName).head_portrait)
        content_dict["to_img"] = "/media/" + to_img if to_img else "/static/personal_center/img/头像.png"
        content_dict["from"] = from_people
        content_dict["to_user"] = roomName
        content_dict["read"] = 0
        try:
            chat_obj = chatting_records.objects.get(room_id=room_id)
            content_json = json.loads(chat_obj.content)
            content_json.append(content_dict)
            chat_obj.content = json.dumps(content_json)
            chat_obj.save()
        except:
            chatting_records.objects.create(
                from_user=User.objects.get(job_number=from_people),
                to_user=roomName,
                msg_type='1',
                content=json.dumps([content_dict]),
                room_id=room_id
            )
        returnDict = {'code': 200, 'message': '', "room_id": room_id}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalEthicsAuditView(View):
    def post(self, request):
        audit_note = request.POST.get('audit_note', None)
        id_list = request.POST.get('id_list', None) # [1,2,3,4]
        items = []
        for id in json.loads(id_list):
            obj = EvaluationOfMedicalEthics.objects.get(id=int(id))
            obj.state = 'five'
            obj.save()
            evaluation_opinion_obj = EvaluationOpinion(parent_id=obj, audit_people=request.user, node='three', audit_note=audit_note, state='audit')
            items.append(evaluation_opinion_obj)
        EvaluationOpinion.objects.bulk_create(items)
        returnDict = {'code': 200, 'message': 'success!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 资产登记
class AddAssetView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        product_objs = [{'id': record.id, "name": record.name} for record in Product.objects.all()]
        context = {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid1(),
                   "product_objs": product_objs}
        return render(request, 'personal_center/add_Asset.html', context)

    def post(self, request):
        number = request.POST.get('number', 'dzb-01')
        uuid = request.POST.get('uuid', None)
        product_id = request.POST.get('product_id', None)
        type = request.POST.get('type', None)
        quantity = request.POST.get('quantity', None)
        purchase_date = request.POST.get('purchase_date', None)
        note = request.POST.get('note', None)
        AssetRegistration.objects.create(apply_user=request.user, company=request.user.company, number=number,
                                         uuid=uuid, type=type, quantity=quantity, purchase_date=purchase_date,
                                         note=note, product_id=product_id)
        returnDict = {'code': 200, "message": "创建成功"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class AddAssetDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = AssetRegistration.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.uuid)]
        context = {'realname': real_name, 'position': position, 'department': department, "obj": obj, 'file_list': file_list}
        # 改为资产登记详情页面
        return render(request, 'personal_center/product_details_view.html', context)


class AddAssetListView(View):
    def get(self, request):
        try:
            real_names = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        com = request.user.company
        search_value = request.GET.get("search_data", '')  # 查询标题
        if request.user.username == 'admin':
            if search_value:
                objs = AssetRegistration.objects.filter(name__contains=search_value).order_by('-create_time')
            else:
                objs = AssetRegistration.objects.all().order_by('-create_time')
        else:
            if search_value:
                objs = com.assetregistration_set.filter(name__contains=search_value).order_by('-create_time')
            else:
                objs = com.assetregistration_set.all().order_by('-create_time')
        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)
        objs_lists = [
            {'id': obj.id, 'number': obj.number, 'apply_user': obj.apply_user.real_name, 'company': obj.company.name,
             'purchase_date': obj.purchase_date.strftime("%Y-%m-%d"),
             "file": Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\",
                                                                                                       "/") if Topicsattachments.objects.filter(
                 topics_number=obj.uuid).count() > 0 else '', 'note': obj.note, 'name': obj.product.name} for
            obj in objs_list]
        context = {'objs': objs_lists, 'realname': request.user.real_name, 'position': request.user.post,
                   "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value,
                   "uuid": uuid.uuid4()}
        if not search_value:
            context.pop("search_value")
        # 改为资产登记
        return render(request, 'personal_center/property_register.html', context)


class ProductListView(View):
    def get(self, request):
        try:
            real_names = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post}
        # 改为物料列表
        return render(request, 'personal_center/product_kind_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", None)  # 查询标题
        if search_data:
            objs = Product.objects.filter(name__contains=search_data).order_by('number')
        else:
            objs = Product.objects.all().order_by('number')
        data_list = [{'id': obj.id, 'number': obj.number, 'name': obj.name, 'unit': obj.unit} for obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductView(View):
    def post(self, request):
        number = request.POST.get('number', None)
        name = request.POST.get('name', None)
        unit = request.POST.get('unit', None)
        Product.objects.create(number=number, name=name, unit=unit)
        sequence_obj = Sequence.objects.filter(type='pt').first()
        sequence_obj.sequence += 1
        sequence_obj.next_sequence += 1
        sequence_obj.save()
        returnDict = {'code': 200, "message": "创建成功"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class DeleteProductView(View):
    def post(self, request):
        id = request.POST.get("id", None)
        try:
            obj = Product.objects.get(id=id)
            obj.delete()
            returnDict = {'code': 200, "message": "删除成功！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except Exception as e:
            returnDict = {'code': 500, "message": "删除失败！%s" % e}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class RealTimeInventoryView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': position, 'department': department}
        # 改为实时库存列表
        return render(request, 'personal_center/product_total_details_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = RealTimeInventory.objects.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'product': obj.product.name, 'qty': obj.qty, 'uint': obj.product.unit,
                      'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M")}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductPurchaseListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': position,'department': department}
        # 物料采购列表页
        return render(request, 'personal_center/product_buy_list_detail.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'audit')  # apply 我的申请 audit 我的待办 already 我的已办
        if tab == 'apply':
            objs = user.productpurchase_set.all().order_by('-create_time')
        elif tab == 'already':
            objs = user.product_purchase_already_audit_users.all().order_by('-create_time')
        else:
            objs = user.product_purchase_users.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'number': obj.number, 'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name, 'total_qty': obj.total_amount, 'state': obj.get_state_display(),
                      'date': obj.date.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductPurchaseView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        phone = request.user.mobile
        product_objs = Product.objects.all()
        list_objs = [{'groupId': 1, 'id': item.id, "groupName": "搜索", 'number': item.number, 'name': item.name,
                      "unit": item.unit} for item in product_objs]

        context = {'realname': real_name, 'position': position, 'department': department, 'phone': phone,
                   'product_objs': list_objs, 'state': 'true'}
        # 改为物料采购页面
        return render(request, 'personal_center/product_order_page.html', context)

    def post(self, request):
        user = request.user
        date = request.POST.get('date', None) # 采购日期
        total_amount = request.POST.get('total_amount', None) # 总金额
        line_list = request.POST.get('line_list', None)  # [{'product_id': 1, 'qty': 1, 'unit': '台', 'price': 100, 'amount': 100}] json格式
        number = ""
        seq_obj = Sequence.objects.filter(type='zc')
        if seq_obj.count():
            seq_obj = seq_obj.first()
            number = 'JSYY-' + str(user.company.abbreviation) + '-ZC-' + str(seq_obj.next_sequence).zfill(4)
            seq_obj.next_sequence += 1
            seq_obj.sequence += 1
            seq_obj.save()
        obj = ProductPurchase.objects.create(apply_user=request.user, company=request.user.company, total_amount=total_amount, date=date.strip(), number=number)
        line_list = json.loads(line_list)
        for line in line_list:
            ProductPurchaseLine.objects.create(adopt=obj, product_id=line['product_id'], qty=line['qty'], unit=line['unit'], price=line['price'], amount=line['amount'])
        # 审批列表待前端确认
        form_obj = AuditForm.objects.filter(name='purchase').first()
        if form_obj:
            audit_list = deal_process_html(json.loads(form_obj.process_json))
            for audit in audit_list:
                if audit['type'] == 'branch':
                    com = Company.objects.filter(name=audit['value']).first()
                    audit_people = com.head_people
                    ProductPurchaseAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
                elif audit['type'] == 'staff':
                    fg = re.findall('\((.*?)\)', audit['value'])
                    audit_people = User.objects.filter(job_number=fg[0]).first()
                    ProductPurchaseAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
                else:
                    if audit['value'] == '分管领导':
                        audit_people = user.company.leaders_id
                        ProductPurchaseAuditRecord.objects.create(parent_id=obj, state='unaudit',
                                                                  audit_people=audit_people,
                                                                  audit_note='', node=audit['value'],
                                                                  seq=int(audit['num']))
                    else:
                        com = user.company
                        audit_people = com.head_people
                        ProductPurchaseAuditRecord.objects.create(parent_id=obj, state='unaudit',
                                                                  audit_people=audit_people,
                                                                  audit_note='', node=audit['value'],
                                                                  seq=int(audit['num']))
            audits = obj.productpurchaseauditrecord_set.filter(seq=1)
            for audit in audits:
                obj.current_audit_users.add(audit.audit_people)

        returnDict = {'code': 200, "message": "创建成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductPurchaseDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get("id", None)
        obj = ProductPurchase.objects.get(id=id)
        line_objs = obj.productpurchaseline_set.all()
        audit_list = []
        for audit_obj in obj.productpurchaseauditrecord_set.all().order_by('seq'):
            audit_list.append(
                {'audit_user': audit_obj.audit_people.real_name,
                 'state': audit_obj.get_state_display(),
                 'node': audit_obj.node,
                 'audit_note': audit_obj.audit_note,
                 'audit_time': audit_obj.update_time.strftime(
                     "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                 'signature_picture': '/media/' + str(
                     audit_obj.audit_people.signature_picture) if (
                         audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}
            )
        context = {'realname': real_name, 'position': position, 'department': department, 'obj': obj,
                   'line_objs': line_objs, 'audit_list': audit_list,
                   'is_audit': 'true' if request.user in obj.current_audit_users.all() and obj.state == 'one' else 'false',
                   'is_cancel': 'true' if request.user == obj.apply_user and obj.state == 'two' else 'false',
                   'is_stop': 'true' if request.user == obj.apply_user and obj.state == 'one' else 'false',
                   'is_recall': 'true' if request.user == obj.apply_user and obj.state == 'one' and obj.productpurchaseauditrecord_set.filter(
                       state__in=['draft', 'audit']).count() == 0 else 'false'}
        # 改为物料采购详情页面
        return render(request, 'personal_center/product_shenpi_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = ProductPurchase.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        audit_record_obj = obj.productpurchaseauditrecord_set.filter(state='unaudit',
                                                                     audit_people=request.user).order_by(
            "seq").first()
        audit_record_obj.state = state
        audit_record_obj.audit_note = audit_note
        audit_record_obj.update_time = datetime.now()
        audit_record_obj.save()
        try:
            if state == 'audit':
                audit_record = obj.productpurchaseauditrecord_set.filter(state='unaudit', seq=audit_record_obj.seq)
                if audit_record.count() == 0:
                    next_audit_record_objs = obj.productpurchaseauditrecord_set.filter(state='unaudit',
                                                                                       seq=audit_record_obj.seq + 1)
                    if next_audit_record_objs.count() == 0:
                        obj.state = 'two'
                        obj.save()
                        obj.current_audit_users.clear()
                        seq_obj = Sequence.objects.filter(type='stock')
                        if seq_obj.count():
                            seq_obj = seq_obj.first()
                            number = 'JSYYRKD' + str(seq_obj.next_sequence).zfill(4)
                            seq_obj.next_sequence += 1
                            seq_obj.sequence += 1
                            seq_obj.save()
                        else:
                            Sequence.objects.create(type='stock', sequence=1, next_sequence=2)
                            number = 'JSYYRKD0001'
                        stock_obj = StockManage.objects.create(number=number, purchase=obj, type='inner',
                                                               state='draft')
                        for line in obj.productpurchaseline_set.all():
                            StockManageLine.objects.create(stock=stock_obj, product=line.product, qty=line.qty,
                                                           unit=line.unit, price=line.price, amount=line.amount)

                    else:
                        obj.current_audit_users.clear()
                        for next_audit_record_obj in next_audit_record_objs:
                            obj.current_audit_users.add(next_audit_record_obj.audit_people)
                else:
                    obj.current_audit_users.remove(request.user)
            else:
                obj.state = 'four'
                obj.save()
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)
        except Exception as e:
            obj.state = 'one'
            obj.current_audit_users.add(request.user)
            obj.save()
            returnData = {'code': 500, 'message': '审批错误%s！' % e}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ProductPurchaseCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = ProductPurchase.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'two':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的物资采购申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.productpurchaseauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的物资采购申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'two':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的物资采购申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class AuditFormView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        # objs = AuditForm.objects.all()
        context = {'realname': real_name, 'position': position,
                   'department': department}
        # 改为自定义审批界面
        return render(request, "system_setup/audit_form_view.html", context)

    def post(self, request):
        name = request.POST.get('name', '')
        process_html = request.POST.get('process_html', '')
        process_json = request.POST.get('process_json', '')
        if AuditForm.objects.filter(name=name).count() > 0:
            if name == 'apply':
                name = '物资申请'
            elif name == 'purchase':
                name = '物资采购'
            returnDict = {'code': 500, 'message': '%s已创建审批流程。请勿重复创建！' % name}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        AuditForm.objects.create(apply_user=request.user, name=name,
                                 process_html=process_html, process_json=process_json)
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class AuditFormDeatilView(View):
    def get(self, request):
        real_name = request.user.real_name
        position = request.user.post
        department = request.user.company.name
        # id = request.GET.get('id', None)
        objs = AuditForm.objects.all()
        process_name = request.GET.get("process_name", None)
        context = {'realname': real_name, 'position': position,
                   'department': department, 'objs': objs, "process_name": process_name}
        # 改为自定义审批界面
        return render(request, "system_setup/product_define_html.html", context)

    def post(self, request):
        id = request.GET.get('id', None)
        obj = AuditForm.objects.get(id=id)
        process_html = request.POST.get('process_html', '')
        process_json = request.POST.get('process_json', '')
        obj.process_html = process_html
        obj.process_json = process_json
        obj.save()
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductUpdate(View):
    def get(self, request):
        objs = AuditForm.objects.all()
        context = {'objs': objs}
        return render(request, "system_setup/produce_update_define.html", context)

    def post(self, request):
        id = request.POST.get('id', None)
        obj = AuditForm.objects.get(id=id)
        process_html = request.POST.get('process_html', '')
        process_json = request.POST.get('process_json', '')
        obj.process_html = process_html
        obj.process_json = process_json
        obj.save()
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class StockManageListView(View):
    def get(self, request):
        sql = '''
            SELECT
            type,
            sum(num)
            from
            (SELECT
            type,
            COUNT(type) as num
            from personal_center_stockmanage GROUP BY type
            union all
            SELECT
            'inner' as  type,
            0 as num
            union all
            SELECT
            'out' as  type,
            0 as num) base GROUP BY type
        
        '''
        one_dict = {}
        with connection.cursor() as cursor:
            cursor.execute(sql)
            all_data = cursor.fetchall()
            for i in all_data:
                one_dict[i[0]] = i[1]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, "one_dict": one_dict}
        # 物料入库列表
        return render(request, 'personal_center/product_stock_manage_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.GET.get("tab", 'audit')  # apply 我的申请 audit 我的待办 already 我的已办
        if search_data:
            objs = StockManage.objects.all().order_by('-create_time')
        else:
            objs = StockManage.objects.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'number': obj.number, 'state': obj.get_state_display(),
                      'type': obj.get_type_display(),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()])}
                     for obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class StockManageView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get("id", None)
        obj = StockManage.objects.get(id=id)
        line_objs = obj.stockmanageline_set.all()
        context = {'realname': real_name, 'position': position, 'department': department, 'obj': obj,
                   'line_objs': line_objs}
        # 改为物料入库详情
        return render(request, 'personal_center/product_purchase_order.html', context)

    def post(self, request):
        id = request.POST.get("id", None)
        obj = StockManage.objects.get(id=int(id))
        line_ids = request.POST.get("line_ids", None)  # [{'id': 1,'real_qty': 50}]
        if obj.state != 'draft':
            returnDict = {'code': 500, 'message': '状态不正确！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        line_ids = json.loads(line_ids)
        for line in line_ids:
            line_obj = StockManageLine.objects.get(id=line['id'])
            line_obj.real_qty = line['real_qty']
            line_obj.save()

        with transaction.atomic():
            # 下面这段代码在事务中执行
            # 创建事务保存点
            sid = transaction.savepoint()
            try:
                for line in obj.stockmanageline_set.all():
                    real_objs = RealTimeInventory.objects.filter(product=line.product)
                    if real_objs.count():
                        real_obj = real_objs.first()
                        if obj.type == 'inner':
                            real_obj.qty += line.real_qty
                        else:
                            if real_obj.qty < line.real_qty:
                                transaction.savepoint_rollback(sid)
                                returnData = {'code': 500, 'message': '库存不够！出库失败 '}
                                return HttpResponse(json.dumps(returnData), content_type="application/json")
                            else:
                                real_obj.qty -= line.real_qty
                        real_obj.save()
                    else:
                        if obj.type == 'inner':
                            RealTimeInventory.objects.create(product=line.product, qty=line.real_qty)
                        else:
                            transaction.savepoint_rollback(sid)
                            returnData = {'code': 500, 'message': '出库失败！'}
                            return HttpResponse(json.dumps(returnData), content_type="application/json")
            except Exception as e:
                # 如发生异常，回滚到指定地方。
                transaction.savepoint_rollback(sid)
                # 如果没有异常，显式地提交一次事务
            obj.state= 'confirm'
            obj.save()
            transaction.savepoint_commit(sid)
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductApplyListView(View):
    def get(self, request):
        user = request.user
        context = {'realname': request.user.real_name, 'position': request.user.post}
        # 物料领用页面
        return render(request, 'personal_center/product_apply_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'audit')  # apply 我的申请 audit 我的待办 already 我的已办
        if tab == 'apply':
            objs = user.productadopt_set.all().order_by('-create_time')
        elif tab == 'audit':
            objs = user.product_adopt_users.all().order_by('-create_time')
        else:
            objs = user.product_adopt_already_audit_users.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'number': obj.number, 'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name, 'total_qty': obj.total_qty,
                      'date': obj.date.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'state': obj.get_str_state()}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        product_objs = Product.objects.all()
        list_objs = [{'groupId': 1, 'id': item.id, "groupName": "搜索", 'number': item.number, 'name': item.name,
                      "unit": item.unit, "real_qty": item.get_real_qty()} for item in product_objs]
        context = {'realname': real_name, 'position': position, 'department': department, 'product_objs': list_objs}
        return render(request, 'personal_center/product_apply_view.html', context)

    def post(self, request):
        user = request.user
        date = request.POST.get('date', None)  # 采购日期
        total_qty = request.POST.get('total_qty', 0)  # 总数量
        line_list = request.POST.get('line_list', None)  # [{'product_id': 1, 'qty': 1, 'unit': '台'}] json格式
        note = request.POST.get('note', None)  # 备注

        form_obj = AuditForm.objects.filter(name='apply').first()
        if not form_obj:
            returnDict = {'code': 500, "message": "未配置审批流程！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        seq_obj = Sequence.objects.filter(type='zc')
        number = ''
        if seq_obj.count():
            seq_obj = seq_obj.first()
            number = 'JSYY-' + str(user.company.abbreviation) + '-ZC-' + str(seq_obj.next_sequence).zfill(4)
            seq_obj.next_sequence += 1
            seq_obj.sequence += 1
            seq_obj.save()
        obj = ProductAdopt.objects.create(apply_user=request.user, company=request.user.company, total_qty=total_qty, date=date.strip(), note=note, number=number)
        line_list = json.loads(line_list)
        for line in line_list:
            ProductAdoptLine.objects.create(adopt=obj, product_id=line['product_id'], qty=line['qty'], unit=line['unit'])
        # 审批列表待前端确认

        if form_obj:
            audit_list = deal_process_html(json.loads(form_obj.process_json))
            for audit in audit_list:
                if audit['type'] == 'branch':
                    com = Company.objects.filter(name=audit['value']).first()
                    audit_people = com.head_people
                    ProductAdoptAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
                elif audit['type'] == 'staff':
                    fg = re.findall('\((.*?)\)', audit['value'])
                    audit_people = User.objects.filter(job_number=fg[0]).first()
                    ProductAdoptAuditRecord.objects.create(parent_id=obj, state='unaudit', audit_people=audit_people,
                                                              audit_note='', node=audit['value'], seq=int(audit['num']))
                else:
                    if audit['value'] == '分管领导':
                        audit_people = user.company.leaders_id
                        ProductAdoptAuditRecord.objects.create(parent_id=obj, state='unaudit',
                                                                  audit_people=audit_people,
                                                                  audit_note='', node=audit['value'],
                                                                  seq=int(audit['num']))
                    else:
                        com = user.company
                        audit_people = com.head_people
                        ProductAdoptAuditRecord.objects.create(parent_id=obj, state='unaudit',
                                                                  audit_people=audit_people,
                                                                  audit_note='', node=audit['value'],
                                                                  seq=int(audit['num']))
            audits = obj.productadoptauditrecord_set.filter(seq=1)
            for audit in audits:
                obj.current_audit_users.add(audit.audit_people)

        returnDict = {'code': 200, "message": "创建成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProductAdoptDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get("id", None)
        obj = ProductAdopt.objects.get(id=id)
        line_objs = obj.productadoptline_set.all()
        audit_list = []
        for audit_obj in obj.productadoptauditrecord_set.all().order_by('seq'):
            audit_list.append(
                {'audit_user': audit_obj.audit_people.real_name,
                 'state': audit_obj.get_state_display(),
                 'node': audit_obj.node,
                 'audit_note': audit_obj.audit_note,
                 'audit_time': audit_obj.update_time.strftime(
                     "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                 'signature_picture': '/media/' + str(
                     audit_obj.audit_people.signature_picture) if (
                         audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}
            )
        context = {'realname': real_name, 'position': position, 'department': department, 'obj': obj,
                   'line_objs': line_objs, 'audit_list': audit_list,
                   'is_audit': 'true' if request.user in obj.current_audit_users.all() and obj.state == 'one' else 'false',
                   'is_cancel': 'true' if request.user == obj.apply_user and obj.state == 'two' else 'false',
                   'is_stop': 'true' if request.user == obj.apply_user and obj.state == 'one' else 'false',
                   'is_recall': 'true' if request.user == obj.apply_user and obj.state == 'one' and obj.productadoptauditrecord_set.filter(
                       state__in=['draft', 'audit']).count() == 0 else 'false',
                   }
        # 改为物料领用详情页面
        return render(request, 'personal_center/product_apply_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = ProductAdopt.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        audit_record_obj = obj.productadoptauditrecord_set.filter(state='unaudit', audit_people=request.user).order_by(
            "seq").first()
        audit_record_obj.state = state
        audit_record_obj.audit_note = audit_note
        audit_record_obj.update_time = datetime.now()
        audit_record_obj.save()
        if state == 'audit':
            audit_record = obj.productadoptauditrecord_set.filter(state='unaudit', seq=audit_record_obj.seq)
            if audit_record.count() == 0:
                next_audit_record_objs = obj.productadoptauditrecord_set.filter(state='unaudit',
                                                                                   seq=audit_record_obj.seq + 1)
                if next_audit_record_objs.count() == 0:
                    obj.state = 'two'
                    obj.save()
                    obj.current_audit_users.clear()
                    seq_obj = Sequence.objects.filter(type='stock')
                    if seq_obj.count():
                        seq_obj = seq_obj.first()
                        number = 'JSYYRKD' + str(seq_obj.next_sequence).zfill(4)
                    else:
                        Sequence.objects.create(type='stock', sequence=1, next_sequence=2)
                        number = 'JSYYRKD0001'
                    stock_obj = StockManage.objects.create(number=number, adopt=obj, type='out', state='draft')
                    for line in obj.productadoptline_set.all():
                        StockManageLine.objects.create(stock=stock_obj, product=line.product, qty=line.qty,
                                                       unit=line.unit, price=0, amount=0)

                else:
                    obj.current_audit_users.clear()
                    for next_audit_record_obj in next_audit_record_objs:
                        obj.current_audit_users.add(next_audit_record_obj.audit_people)
            else:

                obj.current_audit_users.remove(request.user)
        else:
            obj.state = 'four'
            obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(obj.apply_user)

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ProductAdoptCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = ProductAdopt.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'two':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的物资领用申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.productadoptauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的物资领用申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'two':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的物资领用申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 资产审批流程列表
class DefineProducePage(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': position, 'department': department}
        return render(request, "system_setup/define_produce_view.html", context)


# 印章列表
class Stamp_List(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        obj_all = seal.objects.all()
        seal_list = [{"seal_name": i.seal_name, "save_prople": i.save_prople, "explain": i.explain, "watermark_pic": i.watermark_pic} for i in obj_all]

        context = {'realname': real_name, 'position': position, 'department': department, "seal_list": seal_list}
        return render(request, "personal_center/stamp_list.html", context)

    def post(self, request):            # 保存印章信息
        seal_name = request.POST.get("seal_name", "")               # 印章名称
        save_prople = request.POST.get("save_prople", "")           # 保管人
        explain = request.POST.get("explain", "")                   # 说明
        obj_id = request.POST.get("obj_id", "")                     # 印章ID

        seal_obj = seal.objects.get(id=obj_id)
        seal_obj.seal_name = seal_name
        seal_obj.save_prople = save_prople
        seal_obj.explain = explain
        seal_obj.save()
        returnData = {'code': 200, 'message': '保存成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 上传印章
class upload_watermark(View):
    def post(self, request):            # 保存印章信息
        files = request.FILES.get('files')
        file_name = files.name
        watermark_pic_obj = seal.objects.create(
            pic=files,
            watermark_pic="",
            pic_name=file_name,
            save_prople="",
            explain=""
        )
        pic_path = str(watermark_pic_obj.pic).replace(os.path.basename(str(watermark_pic_obj.pic)), file_name)
        watermark_pic_obj.pic = pic_path
        watermark_pic = add_watermark(os.getcwd() + "/media/" + pic_path)+"/"+file_name
        watermark_pic_obj.watermark_pic = watermark_pic
        watermark_pic_obj.save()
        returnData = {'code': 200, 'message': '审核成功！', "id": watermark_pic_obj.id, "src": watermark_pic}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 生成议题上会文件
class Generate_files(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)
        file_name = request.POST.get("file_name", None)
        iss_type = request.POST.get("iss_type", None)
        meeting_adress = request.POST.get("meeting_adress", None)
        meeting_time = request.POST.get("meeting_time", None)

        id_str = ''.join([str(i) for i in json.loads(id_list)])

        pass_yb_list = []
        no_pass_yb = []
        if iss_type == "db":
            for ii in json.loads(id_list):
                yiti_yb_obj = Topics.objects.get(id=int(ii))
                if yiti_yb_obj.is_yb:
                    pass_yb_list.append(ii)
                else:
                    no_pass_yb.append(ii)
            id_list = json.dumps(pass_yb_list + no_pass_yb)
        # *********************************** 生成pdf文件 ****************************************
        pdf_file_list = []
        page_list = []
        for i in json.loads(id_list):
            one_dict = {}
            yiti_yb_obj = Topics.objects.get(id=int(i))
            one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
            one_dict["title"] = yiti_yb_obj.topics_name
            one_dict["dep"] = yiti_yb_obj.employee.company.name
            one_dict["tjr"] = yiti_yb_obj.employee.real_name
            one_dict["ytbh"] = yiti_yb_obj.number
            one_dict["ygys"] = yiti_yb_obj.topics_estimate
            one_dict["nrwb"] = yiti_yb_obj.nrwb
            one_dict["zcyj"] = yiti_yb_obj.zcwb
            one_dict["fawb"] = yiti_yb_obj.fawb
            one_dict["ysje"] = yiti_yb_obj.ysje
            one_dict["jfly"] = yiti_yb_obj.jfly
            one_dict["nrwb_base"] = yiti_yb_obj.topics_text
            one_dict["fawb_base"] = yiti_yb_obj.solution
            one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
            audit_dic = {}
            for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': os.getcwd() + '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': os.getcwd() + '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            one_dict["audit_dic"] = audit_dic
            if iss_type == "yb":
                file_path = directory().yb_func(one_dict, iss_type, file_name)
            elif iss_type == "db":
                file_path = directory().db_func(one_dict, iss_type, file_name)
            else:
                file_path = directory().xz_func(one_dict, iss_type, file_name)

            pdf_file_list.append(file_path)
            text_page = get_num_pages(file_path)
            pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_yb_obj.uuid, file_type="0")
            for path in pdf_path_list:
                pdf_file_path = os.getcwd() + path.pdf_path
                if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                    if path.pdf_path.split('.')[-1] in ['pdf', 'PDF']:
                        pdf_file_list.append(pdf_file_path)
                        enclosure_page = get_num_pages(pdf_file_path)
                        text_page += enclosure_page
                    elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                        pdf_tp_path = image_to_pdf(pdf_file_path)
                        pdf_file_list.append(pdf_tp_path)
                        enclosure_page = get_num_pages(pdf_tp_path)
                        text_page += enclosure_page

            page_list.append(text_page)

        file_merger = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        for pdf in pdf_file_list:
            try:
                print("===========", pdf)
                file_merger.append(pdf)  # 合并pdf文件
            except:
                continue
        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file"
        if not os.path.exists(Issue_information_path):
            os.makedirs(Issue_information_path)
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料_numbered.pdf"  # PDF 议题资料路径
        file_merger.write(pdf_path)

        # add_page_numgers(pdf_path)
        # *********************************** 生成excel文件 ****************************************
        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict = [], [], [], {}, {}, {}
        if iss_type == 'yb':
            Yb_AllList = []
            for i in range(len(json.loads(id_list))):
                Ybobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                TOPICTYPE = '付款类' if Ybobj.topic_type == '1' else "经济合同类" if Ybobj.topic_type == '2' else "项目类" if Ybobj.topic_type == '3' else "文件类" if Ybobj.topic_type == '4' else "方案类" if Ybobj.topic_type == '5' else "其他事项" if Ybobj.topic_type == '6' else ""
                yb_list = [Ybobj.topics_name, Ybobj.employee.company.name, Ybobj.employee.real_name,
                           str(Ybobj.create_time).split(".")[0][:-3],
                           str(Ybobj.topicsauditrecord_set.all().order_by('update_time').last().update_time).split(".")[0][:-3],
                           Ybobj.employee.company.leaders_id.real_name, Ybobj.id, TOPICTYPE]

                if Ybobj.employee.department in YbDict:
                    YbDict[Ybobj.employee.department].append(yb_list)
                else:
                    YbDict[Ybobj.employee.department] = [yb_list]

            for iJ in YbDict:
                Yb_AllList += YbDict[iJ]

            for ij in range(len(Yb_AllList)):
                Yb_AllList[ij].insert(0, ij + 1)
                start_page = sum(page_list[:ij])+1
                end_page = sum(page_list[:ij+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Yb_AllList[ij].append(page_number)
                YbAllList.append(Yb_AllList[ij])

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/yb"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            create_table().yb_excel(YbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)

        elif iss_type == 'db':
            YbZhuanDbAllList, YbZhuanDbAllDict, YbDbAllDict, Db_AllList, Db_zh_alllidt, Db_all_list, Yb_ZhuanDbAllList = [], {}, {}, [], [], [], []
            for i in range(len(json.loads(id_list))):
                Dbobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                db_dict = [Dbobj.topics_name, Dbobj.employee.company.name, Dbobj.employee.real_name,
                           str(Dbobj.create_time).split(".")[0][:-3], str(Dbobj.update_time).split(".")[0][:-3],
                           Dbobj.employee.company.head_people.real_name, Dbobj.id]
                print(db_dict)
                if Dbobj.is_yb:
                    if Dbobj.employee.department in YbZhuanDbAllDict:
                        YbZhuanDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbZhuanDbAllDict[Dbobj.employee.department] = [db_dict]

                else:
                    if Dbobj.employee.department in YbDbAllDict:
                        YbDbAllDict[Dbobj.employee.department].append(db_dict)
                    else:
                        YbDbAllDict[Dbobj.employee.department] = [db_dict]

            for Tj in YbZhuanDbAllDict:
                Db_zh_alllidt += YbZhuanDbAllDict[Tj]
            for TT in range(len(Db_zh_alllidt)):
                Db_zh_alllidt[TT].insert(0, TT + 1)
                new_list = Db_zh_alllidt[TT][:2]
                new_list.append(Db_zh_alllidt[TT][-1])
                YbZhuanDbAllList.append(new_list)

            for ij in range(len(YbZhuanDbAllList)):
                start_page = sum(page_list[:ij])+1
                end_page = sum(page_list[:ij+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                YbZhuanDbAllList[ij].append(page_number)
                Yb_ZhuanDbAllList.append(YbZhuanDbAllList[ij])

            for JJ in YbDbAllDict:
                Db_all_list += YbDbAllDict[JJ]
            for TJ in range(len(Db_all_list)):
                Db_all_list[TJ].insert(0, TJ + 1)
                Db_AllList.append(Db_all_list[TJ])

            page_start = len(YbZhuanDbAllList)
            for ij in range(len(Db_AllList)):
                start_page = sum(page_list[:page_start])+1
                end_page = sum(page_list[:page_start+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                Db_AllList[ij].append(page_number)
                DbAllList.append(Db_AllList[ij])
                page_start += 1
            file_path = os.getcwd() + f"/media/Issue_information/excel_file/db"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            create_table().db_excel(Yb_ZhuanDbAllList, DbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)

        else:
            Xz_AllList = []
            for i in range(len(json.loads(id_list))):
                Xzobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
                # mobiles.append(Xzobj.employee.mobile)
                lh_dict = [Xzobj.topics_name, Xzobj.employee.company.name, Xzobj.employee.real_name,
                           str(Xzobj.create_time).split(".")[0][:-3],
                           str(Xzobj.update_time).split(".")[0][:-3], Xzobj.employee.company.leaders, Xzobj.id]
                if Xzobj.employee.department in LhDict:
                    LhDict[Xzobj.employee.department].append(lh_dict)
                else:
                    LhDict[Xzobj.employee.department] = [lh_dict]
            Lh_AllList = []
            for IY in LhDict:
                Lh_AllList += LhDict[IY]

            for Yi in range(len(Lh_AllList)):
                Lh_AllList[Yi].insert(0, Yi + 1)
                XzAllList.append(Lh_AllList[Yi])

            for IJ in range(len(XzAllList)):
                start_page = sum(page_list[:IJ])+1
                end_page = sum(page_list[:IJ+1])
                page_number = f"{start_page}-{end_page}页"
                if start_page == end_page:
                    page_number = f"{start_page}页"
                XzAllList[IJ].append(page_number)
                Xz_AllList.append(XzAllList[IJ])

            file_path = os.getcwd() + f"/media/Issue_information/excel_file/xz"
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            create_table().yb_excel(Xz_AllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
        FilePath = os.getcwd() + f"/media/files/{file_name}.txt"
        with open(FilePath, "w+", encoding="utf-8") as f1:
            f1.write(id_str)

        returnData = {'code': 200, 'message': '成功！', "excel_path": file_path + f"/{file_name}-会议目录.xlsx", "pdf_path": f"{Issue_information_path}/{file_name}-会议资料.pdf"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 固定资产付款流程
class FixedAssetsApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid1(),}
        return render(request, 'personal_center/fixed_assets_apply_view.html', context)

    def post(self, request):
        # user = request.user
        # title = request.POST.get('title', None)         # 付款标题
        # total_money = request.POST.get('total_money', 0)     # 付款总金额
        # id = request.POST.get('id', None)
        # company = request.user.company     # 上传科室
        # financial = request.POST.get('financial', '')               # 经费来源
        # fj_number = request.POST.get('fj_number', None)
        # daxie = request.POST.get('daxie', '')           # 付款总金额大写
        # remake = request.POST.get('remake', '')         # 备注
        # detail_pay = request.POST.get('detail_pay', '')               # 付款明细
        # xiugai = request.POST.get('xiugai', '')               # 是否是管理员修改
        # revise = request.POST.get('revise', '')               # 是否是申请人修改
        # payee = request.POST.get('payee', "")                  # 收款单位
        # payee_account = request.POST.get('payee_account', '')   # 收款账号
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "固定资产/维修维保付款")
        # except:
        #     pass
        # message_str = ''
        # if id:
        #     obj = FixedAssets.objects.get(id=id)
        #     obj.apply_user = user
        #     obj.title = title
        #     obj.daxie = daxie
        #     obj.remake = remake
        #     obj.detail_pay = detail_pay
        #     obj.total_money = total_money
        #     obj.company = company
        #     obj.financial = financial
        #     obj.fj_number = fj_number
        #     obj.payee = payee
        #     obj.payee_account = payee_account
        #     obj.save()
        #     if xiugai:
        #         message_str = "修改成功！"
        #     if revise:
        #         message_str = "修改成功！"
        #         obj.current_audit_users.clear()
        #         obj.fixedassetsauditrecord_set.all().delete()
        # else:
        #     obj = FixedAssets.objects.create(number='', apply_user=user, title=title, total_money=total_money,
        #                                      company=company, financial=financial, fj_number=fj_number, daxie=daxie, remake=remake, detail_pay=detail_pay, payee=payee, payee_account=payee_account)
        #
        # if not xiugai or revise:
        #     one_appave = user.company.head_people
        #     flag = True
        #     if user != one_appave:
        #         FixedAssetsAuditRecord.objects.create(node='SBKZ', state='unaudit', audit_people=one_appave, parent_id=obj)
        #         obj.current_audit_users.add(one_appave)
        #         obj.state = 'one'
        #         obj.save()
        #         flag = False
        #
        #     FixedAssetsAuditRecord.objects.create(node='B', state='unaudit', audit_people=user.company.leaders_id, parent_id=obj)
        #     if flag:
        #         obj.current_audit_users.add(user.company.leaders_id)
        #         obj.state = 'three'
        #         obj.save()
        #
        #     cwk_obj = Company.objects.get(id=23).head_people
        #     FixedAssetsAuditRecord.objects.create(node='CWKZ', state='unaudit', audit_people=cwk_obj, parent_id=obj)
        #
        #     if float(total_money.replace(",", "")) >= 200000:
        #         user_audit_people = Staffing.objects.get(station="书记").post_personnel.all().first()
        #     elif 10000 <= float(total_money.replace(",", "")) < 200000:
        #         user_audit_people = Staffing.objects.get(station="院长").post_personnel.all().first()
        #     else:
        #         user_audit_people = Staffing.objects.get(station="工会主席").post_personnel.all().first()
        #     FixedAssetsAuditRecord.objects.create(node='SJ/YZ', state='unaudit', audit_people=user_audit_people, parent_id=obj)
        #
        #     cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        #     FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=obj)
        #     if revise:
        #         message_str = "修改成功！"
        #     else:
        #         message_str = '创建成功！'
        #
        #     # ********************************************** 发送小程序推送 ******************************************
        #     topic_type = "资产维保"
        #     applicant = obj.apply_user.real_name
        #     ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        #     SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        #     for jj in obj.current_audit_users.all():
        #         try:
        #             RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #         except:
        #             pass
        # returnData = {'code': 200, 'message': message_str}
        returnData = {'code': 400, 'message': "该流程已关闭，现已无法申请！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FixedAssetsApplyDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        revise = request.GET.get("revise", '')
        obj = FixedAssets.objects.get(id=id)
        audit_dic = {}
        flow_dict = {}
        for audit_obj in obj.fixedassetsauditrecord_set.all().order_by("update_time"):
            node = "科室负责人" if audit_obj.node == 'SBKZ' else "分管领导" if audit_obj.node == 'B' else "负责人" if audit_obj.node == 'SJ/YZ' else "财务科长" if audit_obj.node == 'CWKZ' else "财务支付"
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.fixedassetsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1, "node": node}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'seven' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', ] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'seven'] and request.user == obj.apply_user else 'false',
                   'user_obj': User.objects.filter(group_id=1),
                   'revise': revise,
                   'detail_pay': json.loads(obj.detail_pay),
                   'flow_dict': flow_dict, "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'personal_center/fixed_assets_apply_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "固定资产/维修维保付款")
        except:
            pass
        obj = FixedAssets.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'one':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='SBKZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'three'
            elif obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'two'
            elif obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'

            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'
            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'two'
            elif obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'

            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'
            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "资产维保"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FixedAssetsApplyListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "personal_center_fixedassets"}
        return render(request, 'personal_center/fixed_assets_apply_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办
        if tab == 'apply':
            objs = user.fixedassets_set.all().order_by('-create_time')
        elif tab == 'already':
            objs = user.fixed_assets_already_audit_users.all().order_by('-create_time')
        else:
            objs = user.fixed_assets_users.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'number': obj.number,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'title': obj.title,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='fixed_assets_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else
                      (f"<a href='fixed_assets_apply_detail_view?id={obj.id}'>查看</a> | <a href='fixed_assets_apply_detail_view?revise=true&id={obj.id}'>修改</a>"
                       if obj.can_revise == '1' and obj.state in ['two', 'one', 'three', 'four']
                       else (f"<a href='fixed_assets_apply_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                             if obj.state == 'stop' else f"<a href='fixed_assets_apply_detail_view?id={obj.id}'>查看</a>")),
                      'state': obj.get_str_state(),
                      'financial': obj.financial,
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 固定资产流程保存草稿
class FixedAssetsApplyDarftView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        obj = FixedAssets.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, 'detail_pay': json.loads(obj.detail_pay)}
        return render(request, 'personal_center/fixed_assets_apply_draft_index.html', context)

    def post(self, request):
        user = request.user
        title = request.POST.get('title', None)  # 付款标题
        total_money = request.POST.get('total_money', 0)  # 付款总金额
        id = request.POST.get('id', None)
        company = request.user.company  # 上传科室
        financial = request.POST.get('financial', '')  # 经费来源
        fj_number = request.POST.get('fj_number', None)
        daxie = request.POST.get('daxie', '')  # 付款总金额大写
        remake = request.POST.get('remake', '')  # 备注
        detail_pay = request.POST.get('detail_pay', '')  # 付款明细
        payee = request.POST.get('payee', "")
        payee_account = request.POST.get('payee_account', '')

        if id:
            obj = FixedAssets.objects.get(id=id)
            obj.apply_user = user
            obj.state = 'draft'
            obj.title = title
            obj.daxie = daxie
            obj.remake = remake
            obj.detail_pay = detail_pay
            obj.total_money = total_money
            obj.company = company
            obj.financial = financial
            obj.fj_number = fj_number
            obj.payee = payee
            obj.payee_account = payee_account
            obj.save()
        else:
            obj = FixedAssets.objects.create(number='', apply_user=user, state='draft',
                                             title=title, total_money=total_money,
                                             company=company, financial=financial, fj_number=fj_number, daxie=daxie,
                                             remake=remake, detail_pay=detail_pay, payee=payee, payee_account=payee_account)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 固定资产流程修改
class FixedAssetsWriteView(View):
    def post(self, request):
        id = request.POST.get("id", None)
        obj = FixedAssets.objects.get(id=int(id))
        if obj.state != 'seven':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        title = request.POST.get('title', None)  # 付款标题
        total_money = request.POST.get('total_money', 0)  # 付款总金额
        company = request.user.company  # 上传科室
        financial = request.POST.get('financial', '')  # 经费来源
        fj_number = request.POST.get('fj_number', None)
        daxie = request.POST.get('daxie', '')  # 付款总金额大写
        remake = request.POST.get('remake', '')  # 备注
        detail_pay = request.POST.get('detail_pay', '')  # 付款明细

        obj.title = title
        obj.total_money = total_money
        obj.company = company
        obj.financial = financial
        obj.fj_number = fj_number
        obj.daxie = daxie
        obj.remake = remake
        obj.detail_pay = detail_pay

        obj.current_audit_users.clear()
        # obj.fixedassetsauditrecord_set.filter(state='unaudit').delete()
        flag = True
        if obj.fixedassetsauditrecord_set.filter(node='SBKZ'):
            obj.state = 'one'
            flag = False
            audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='SBKZ').last()
            obj.current_audit_users.add(audit_record_obj.audit_people)
            if obj.fixedassetsauditrecord_set.filter(node='SBKZ', state='unaudit').count() == 0:
                audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='SBKZ').last()
                FixedAssetsAuditRecord.objects.create(node='SBKZ', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

        if flag:
            obj.state = 'two'
            audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='CWKZ').last()
            obj.current_audit_users.add(audit_record_obj.audit_people)

        if obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').count() == 0:
            audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='CWKZ').first()
            FixedAssetsAuditRecord.objects.create(node='CWKZ', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

        if obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit').count() == 0:
            audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='B').first()
            FixedAssetsAuditRecord.objects.create(node='B', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

        yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        gh_obj = Company.objects.get(id=23).leaders_id
        obj.fixedassetsauditrecord_set.filter(node='SJ/YZ').delete()
        FixedAssetsAuditRecord.objects.create(parent_id=obj, audit_people=yz_obj if 10000 <= float(total_money.replace(",", "")) < 200000 else sj_obj if float(total_money.replace(",", "")) >= 200000 else gh_obj,
                                                 audit_note='', state='unaudit', node='SJ/YZ')

        if obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').count() == 0:
            audit_record_obj = obj.fixedassetsauditrecord_set.filter(node='CWK').first()
            FixedAssetsAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FixedAssetsRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = FixedAssets.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.fixedassetsauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicDeliberation(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        types = request.GET.get("type", '')
        objs = topic_meeting.objects.filter(state__in=['notstart', 'voting', 'adopt', 'suspension'], topic_type=types, MeetingStatus='progress').order_by("meet_time")
        leaders_list, lerder_flag, reason = [], '', ''
        if objs:
            if not objs.first().voteleader_set.all():
                lerder_flag = '0'
                lerder_obj = User.objects.filter(group_id__in=[1, 2])
                for tt in lerder_obj:
                    leaders_list.append({"leaders": tt.real_name, "job_number": tt.job_number, "Participation": 'false', "vote": 'false'})
            else:
                lerder_flag = '1'
                lerder_obj = objs.first().voteleader_set.all()
                reason = lerder_obj.first().reason
                for jj in lerder_obj:
                    if jj.reason:
                        reason = jj.reason
                    leaders_list.append({"leaders": jj.leaders.real_name, "job_number": jj.leaders.job_number, "Participation": jj.Participation, "vote": jj.vote, 'departure_reason': jj.departure_reason if jj.departure_reason else ''})
        all_personnel = Staffing.objects.get(station='议题审核员').post_personnel.all()
        StafFlag = 0
        for i in all_personnel:
            if request.user == i:
                StafFlag = 1
        if objs:
            leave_obj = topic_sing.objects.filter(meet_number=objs.first().meet_number, topic_type=objs.first().topic_type, topic_year=objs.first().topic_year, sing_type="2")
            sing_obj = topic_sing.objects.filter(meet_number=objs.first().meet_number, topic_type=objs.first().topic_type, topic_year=objs.first().topic_year, sing_type="1")

            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'lerder_flag': lerder_flag, 'lerder_obj': leaders_list,
                       'types': types, 'reason': reason, "StafFlag": StafFlag, "leave_obj": leave_obj, "sing_obj": sing_obj, "meet_number": objs.first().meet_number, "topic_year": objs.first().topic_year}
            return render(request, 'personal_center/TopicDeliberation.html', context)
        else:
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'lerder_flag': lerder_flag, 'lerder_obj': leaders_list,
                       'types': types, 'reason': reason, "StafFlag": StafFlag}
            return render(request, 'personal_center/TopicDeliberation.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        types = request.POST.get("types", '')
        objs = topic_meeting.objects.filter(state__in=['notstart', 'voting', 'adopt', 'suspension'], topic_type=types, MeetingStatus='progress').order_by("meet_time").first()

        if objs:
            leaders_list = []
            if not objs.voteleader_set.all():
                lerder_obj = User.objects.filter(group_id__in=[1, 2])
                for tt in lerder_obj:
                    leaders_list.append({"leaders": tt.real_name, "job_number": tt.job_number, "Participation": 'false', "vote": 'false'})
            else:
                lerder_obj = objs.voteleader_set.all()
                for jj in lerder_obj:
                    leaders_list.append({"leaders": jj.leaders.real_name, "job_number": jj.leaders.job_number, "Participation": jj.Participation, "vote": jj.vote})

            if types == "yb":
                topic_title = f"{objs.topic_year}年第{objs.meet_number}次院长办公会"
            elif types == "db":
                topic_title = f"{objs.topic_year}年第{objs.meet_number}次党委会"
            else:
                topic_title = f"{objs.topic_year}年第{objs.meet_number}次行政例会"

            topic_obj = topic_meeting.objects.filter(meet_number=objs.meet_number, topic_type=types, MeetingStatus='progress')
            data_list3, data_list1, data_list2, Serial_Number = [], [], [], 1
            for obj in topic_obj:
                if request.user.group.id in [1, 2]:
                    try:
                        if obj.MeetingStatus == 'ending':
                            voting_results = "完结"
                        else:
                            if obj.voteleader_set.get(leaders=request.user).state == 'voting':
                                voting_results = "未投票"
                            else:
                                voting_results = "已投票"
                    except:
                        voting_results = ""
                else:
                    voting_results = ''

                style_color = " style='color: #CDC9C9'" if voting_results == '已投票' else ''
                pppp = '<a' + style_color + f' href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">{obj.topic.topics_name}</a>'

                one_dict = {'id': obj.id,
                 'topic_id': obj.topic.id,
                 'topic_name': pppp,
                 'topic_number': "<p"+style_color+f">{obj.topic.number}",
                 'company': "<p"+style_color+f">{obj.topic.employee.company.name}",
                 'submitter': "<p"+style_color+f">{obj.topic.employee.real_name}",
                 'submission_time': obj.topic.create_time.strftime("%Y-%m-%d %H:%M"),
                 'is_yb': '是' if obj.topic.is_yb else '否',
                 'meet_result': f'<a {style_color} href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">投票中</a>' if obj.state == "voting" else
                 f'<a style="color: #00FF7F;" href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">通过</a>' if obj.state == "adopt" else
                 f'<a {style_color} href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">未开始</a>' if obj.state == "notstart" else
                 f'<a style="color: #c6ba0c;" href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">暂缓</a>' if obj.state == "suspension" else
                 f'<a style="color: red;" href="vote_detail.html?voting=true&vote_id={obj.id}&id={obj.topic_id}">不通过</a>',
                 'voting_results': voting_results, "Serial_Number": Serial_Number}

                if voting_results == "已投票":
                    data_list1.append(one_dict)
                elif voting_results == "未投票":
                    data_list2.append(one_dict)
                else:
                    data_list3.append(one_dict)
                Serial_Number += 1

            data_list = data_list2 + data_list1 + data_list3
            all_personnel = Staffing.objects.get(station='议题审核员').post_personnel.all()
            flag = 0
            for i in all_personnel:
                if request.user == i:
                    flag = 1

            returnDict = {'status': 'success', "totals": topic_obj.count(), "data": data_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)], "topic_title": topic_title, "flag": flag, 'code': 200}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'status': 'success', "totals": 0, "data": [], "topic_title": ""}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class vote_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        vote_id = request.GET.get("vote_id", None)
        Topic_Obj = topic_meeting.objects.get(id=int(vote_id))
        all_people = Topic_Obj.voteleader_set.filter(vote=True)
        voting_flag = request.GET.get("voting", None)
        all_list = [{
            "real_name": i.leaders.real_name,
            "vote_reluse": "未投票" if i.state == "voting" else "同意" if i.state == "agree" else "反对" if i.state == "opposition" else "弃权",
            "vote_node": i.node, "vote_time": i.update_time.strftime("%Y-%m-%d %H:%M") if i.state != "voting" else "",
            "autograph": '/media/' + str(i.leaders.signature_picture) if i.state != "voting" else ""
        } for i in all_people]

        UpperNextDict = {}

        ThePrevious = topic_meeting.objects.filter(meet_number=Topic_Obj.meet_number, topic_type=Topic_Obj.topic_type, topic_year=Topic_Obj.topic_year, id__lt=int(vote_id)).order_by("-id")
        if ThePrevious:
            UpperNextDict['upper'] = {'obj': ThePrevious.first(), "status": 'true'}
        else:
            UpperNextDict['upper'] = {'obj': '', "status": 'false'}

        NextPrevious = topic_meeting.objects.filter(meet_number=Topic_Obj.meet_number, topic_type=Topic_Obj.topic_type, topic_year=Topic_Obj.topic_year, id__gt=int(vote_id)).order_by("id")
        if NextPrevious:
            UpperNextDict['next'] = {'obj': NextPrevious.first(), "status": 'true'}
        else:
            UpperNextDict['next'] = {'obj': '', "status": 'false'}

        try:
            my_obj = Topic_Obj.voteleader_set.get(~Q(topics_id__state='notstart'), leaders=request.user)
            my_state = my_obj.state
            my_node = my_obj.node
            if my_state == "voting" and my_obj.vote == 'True':
                top_flag = "true"
            else:
                top_flag = "false"

            if my_obj.vote == 'True' and my_state != 'voting':
                modify = "true"
            else:
                modify = "false"
        except:
            top_flag = "false"
            modify = "false"
            my_state, my_node = '', ''

        all_people_count = Topic_Obj.voteleader_set.filter(vote=True, Participation=True).count()  # 参与投票的总人数
        meet_leaders = Topic_Obj.voteleader_set.filter(Participation=True).count()
        VotersNumber = Topic_Obj.voteleader_set.filter(state__in=['agree', 'opposition', 'waiver']).count()  # 已投票人数
        not_meeting_obj = Topic_Obj.voteleader_set.filter(~Q(reason=''))
        not_attending_the_meeting = ", ".join([i.leaders.real_name for i in not_meeting_obj])                    # 未参会人员
        not_meeting_reason = not_meeting_obj.first().reason if not_meeting_obj else ""
        DepartureMeetObj = Topic_Obj.voteleader_set.filter(~Q(departure_reason=''), Participation=False)
        DepartureMeetCount = DepartureMeetObj.count()

        agree_number = round((Topic_Obj.voteleader_set.filter(state='agree').count() / all_people_count)*100, 2) if all_people_count else 0  # 同意人数
        opposition_number = round((Topic_Obj.voteleader_set.filter(state='opposition').count() / all_people_count)*100, 2) if all_people_count else 0  # 反对人数
        waiver_number = round((Topic_Obj.voteleader_set.filter(state='waiver').count() / all_people_count)*100, 2) if all_people_count else 0  # 弃权人数

        host_people = Topic_Obj.voteleader_set.filter(host=True).first().leaders.real_name if Topic_Obj.voteleader_set.filter(host=True) else ""

        topic_status = "投票中" if Topic_Obj.state == "voting" else "通过" if Topic_Obj.state == "adopt" else "未开始" if Topic_Obj.state == "notstart" else "暂缓" if Topic_Obj.state == "suspension" else "不通过"
        if topic_status in ["通过", "暂缓", "不通过"]:
            topic_flag = 'true'
        else:
            topic_flag = 'flase'

        ids = request.GET.get("id", "")
        try:
            topics_obj = Topics.objects.get(id=int(ids))
        except Exception as e:
            returnDict = {'code': 500, 'message': '获取详情失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic = {}
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            data_dic = {'apply_user': topics_obj.employee.real_name,
                        'department': topics_obj.employee.department,
                        'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list,
                        'number': topics_obj.number,
                        'topics_name': topics_obj.topics_name,
                        'topics_text': base64.b64decode(topics_obj.topics_text).decode(),
                        'topics_basis': base64.b64decode(topics_obj.topics_basis).decode(),
                        'solution': base64.b64decode(topics_obj.solution).decode() if topics_obj.solution != "空" else "",
                        'db_topics_text': base64.b64decode(topics_obj.db_topics_text).decode() if topics_obj.db_topics_text else "",
                        'db_topics_basis': base64.b64decode(topics_obj.db_topics_basis).decode() if topics_obj.db_topics_basis else "",
                        'db_solution': base64.b64decode(topics_obj.db_solution).decode() if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate,
                        'help_department': help_department,
                        'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "",
                        'ysje': topics_obj.ysje if topics_obj.ysje else "",
                        'uuid': topics_obj.uuid,
                        'audit_list': audit_dic,
                        'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                        'is_stop': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "refuse", "OPR"] and request.user == topics_obj.employee else 'false',
                        'is_audit': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "PG", "db_one_step", "db_two_step", "db_three_step", "OPR"] and topics_obj.current_audit_user == request.user.real_name else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}

        try:
            if topics_obj.type == 'db' and topics_obj.HouseToParty_id:
                yb_obj = Topics.objects.get(id=topics_obj.HouseToParty_id)
                db_obj = topics_obj
            else:
                yb_obj = topics_obj
                db_obj = ""
            meeting_obj = topic_meeting.objects.get(topic=yb_obj) if yb_obj.state == 'done' else ''
            yb_vote_obj = VoteLeader.objects.filter(topics_id=meeting_obj).first() if yb_obj.state == 'done' else ''

            db_meeting_obj = topic_meeting.objects.get(topic=db_obj) if db_obj and db_obj.state == 'done' else ''
            db_vote_obj = VoteLeader.objects.filter(topics_id=db_meeting_obj).first() if db_obj.state == 'done' else ''
        except Exception as E:
            yb_vote_obj = ""
            db_vote_obj = ""

        received_audit_dic, company_type = {}, ''
        received_file_list = []
        if topics_obj.received_foreign:
            received_obj = topics_obj.received_foreign
            company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
            for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                if audit_obj.node in received_audit_dic:
                    received_audit_dic[audit_obj.node].append(
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    received_audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            received_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"), "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.received_foreign.uuid)]

        DeanFlag = 'true' if request.user == Staffing.objects.get(station='院长').post_personnel.all().first() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "all_list": all_list, "VotersNumber": VotersNumber, "host_people": host_people, "topic_state": topic_status,
                    "topic_flag": topic_flag, "all_people_count": all_people_count, "my_state": my_state, "my_node": my_node, 'types': Topic_Obj.topic_type, "meet_leaders": meet_leaders, "top_flag": top_flag, 'modify': modify,
                    "not_attending_the_meeting": not_attending_the_meeting, "not_meeting_reason": not_meeting_reason, "DepartureMeetCount": DepartureMeetCount, "DepartureMeetObj": DepartureMeetObj, "vote_obj": yb_vote_obj,
                    "agree_number": agree_number, "opposition_number": opposition_number, "waiver_number": waiver_number, "voting_flag": 'true' if voting_flag else "", "UpperNextDict": UpperNextDict, "db_vote_obj": db_vote_obj,
                    "no_join_meet": "true" if Topic_Obj.create_time.strftime("%Y-%m-%d") > "2023-12-31" else "flase", "id": ids, "data_dic": data_dic, "obj": topics_obj, "DeanFlag": DeanFlag, "received_audit_dic": received_audit_dic,
                    "company_type": company_type, "received_file_list": received_file_list}
        return render(request, 'personal_center/vote_detail.html', context)

    def post(self, request):
        vote_node = request.POST.get("vote_node", None)                 # 投票意见
        vote_reluse = request.POST.get("vote_reluse", None)                 # 投票结果
        topic_id = request.POST.get("topic_id", None)                       # 投票表对应的ID
        # try:
        Topic_Obj = topic_meeting.objects.get(id=int(topic_id))
        if Topic_Obj.state == 'notstart':
            returnDict = {'status': 'success', "code": 400, "msg": "对不起！会议还未开始，请耐心等待!"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        topicObj = VoteLeader.objects.get(leaders=request.user, topics_id=Topic_Obj)

        topicObj.update_time = datetime.now()
        topicObj.state = vote_reluse
        topicObj.node = vote_node
        topicObj.save()

        if not VoteLeader.objects.filter(state="voting", vote=True, topics_id=Topic_Obj).count():
            leader_status = VoteLeader.objects.get(topics_id=Topic_Obj, host=True).state
            if Topic_Obj.topic_type == 'yb':
                if leader_status == "agree":
                    Topic_Obj.state = 'adopt'
                elif leader_status == "opposition":
                    Topic_Obj.state = 'nopass'
                else:
                    Topic_Obj.state = 'suspension'
                Topic_Obj.save()
            else:
                if leader_status == "waiver":
                    Topic_Obj.state = 'suspension'
                    Topic_Obj.save()
                else:
                    agree_count = Topic_Obj.voteleader_set.filter(state='agree', vote=True).count()
                    opposition_count = Topic_Obj.voteleader_set.filter(state='opposition', vote=True).count()
                    waiver_count = Topic_Obj.voteleader_set.filter(state='waiver', vote=True).count()
                    maximum_value = max(agree_count, opposition_count, waiver_count)
                    if agree_count == maximum_value:
                        Topic_Obj.state = 'adopt'
                        Topic_Obj.save()
                    elif opposition_count == maximum_value:
                        Topic_Obj.state = 'nopass'
                        Topic_Obj.save()
                    else:
                        Topic_Obj.state = 'suspension'
                        Topic_Obj.save()
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # except Exception as E:
        #     returnDict = {'status': 'success', "code": 400, "msg": "对不起！您不在投票人员中!"}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 投票echarts数据获取
class vote_echarts(View):
    def post(self, request):
        topic_id = request.POST.get("topic_id", None)
        Topic_Obj = topic_meeting.objects.get(id=int(topic_id))
        meet_all_number = Topic_Obj.voteleader_set.filter(Participation=True).count()  # 参会总人数
        all_people_count = Topic_Obj.voteleader_set.filter(vote=True).count()  # 参与投票的总人数
        VotersNumber = Topic_Obj.voteleader_set.filter(state__in=['agree', 'opposition', 'waiver']).count()  # 已投票人数

        agree_number = Topic_Obj.voteleader_set.filter(state='agree').count()             # 同意人数
        opposition_number = Topic_Obj.voteleader_set.filter(state='opposition').count()             # 反对人数
        waiver_number = Topic_Obj.voteleader_set.filter(state='waiver').count()             # 弃权人数

        percentage_list = [round((agree_number/all_people_count)*100, 2), round((opposition_number/all_people_count)*100, 2), round((waiver_number/all_people_count)*100, 2)]
        people_list = [agree_number, opposition_number, waiver_number]
        vote_count = Topic_Obj.voteleader_set.filter(vote=True).count()
        returnDict = {'status': 'success', "code": 400, "VotersNumber": VotersNumber, "all_people_count": meet_all_number, "percentage_list": percentage_list, "people_list": people_list, "vote_count": vote_count}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


def demo(day1, day2):
    time_array1 = time.strptime(day1, "%Y-%m-%d")
    timestamp_day1 = int(time.mktime(time_array1))
    time_array2 = time.strptime(day2, "%Y-%m-%d")
    timestamp_day2 = int(time.mktime(time_array2))
    result = (timestamp_day2 - timestamp_day1) // 60 // 60 // 24
    return result


def get_total_days(leave_type):     # 计算累计天数
    now = datetime.now()
    this_month_start = datetime(now.year, now.month, 1)
    this_month_end = datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])

    leave_days = 0
    if leave_type in ['e', 'f', 'g']:
        aa = LeaveRequest.objects.filter(leave_type=leave_type, state__in=['seven', 'one', 'two', 'three', 'four']).all()
        for ii in aa:
            if ii.end_time < this_month_end and ii.start_time > this_month_start:  # 计算请假时间段在当月 天数
                leave_days += ii.days
            # elif ii.start_time < this_month_start and this_month_start < ii.end_time < this_month_end:       # 计算请假开始时间在上月，结束时间在本月天数：
            #     pass
            elif this_month_start < ii.start_time < this_month_end and ii.end_time > this_month_end:  # 计算请假开始时间在当月，结束时间在下月 天数
                leave_days += ii.days
    return leave_days


class LeaveRequestApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        leave_li = [
            {'value': 'a', 'leave': '年休假'},
            {'value': 'b', 'leave': '婚假'},
            {'value': 'c', 'leave': '丧假'},
            {'value': 'd', 'leave': '事假'},
            {'value': 'e', 'leave': '病假'},
            {'value': 'f', 'leave': '探亲假'},
            {'value': 'g', 'leave': '放射假'},
            {'value': 'h', 'leave': '产假'},
            {'value': 'i', 'leave': '计生假'},
            {'value': 'j', 'leave': '育儿假'},
        ]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1(), 'leave_li': leave_li, 'job_number': request.user.job_number}
        return render(request, 'finance/leave_request_apply_view.html', context)

    def post(self, request):
        apply_user = request.user
        company = request.user.company
        job_num = request.user.job_number
        id = request.POST.get('id', None)
        leave_type = request.POST.get('leave_type', None)       # {'value': 'a', 'leave': '年休假'}
        reason = request.POST.get('reason', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        fj_number = request.POST.get('fj_number', None)
        people_type = request.POST.get('people_type', '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "请假申请")
        except:
            pass
        if leave_type != 'h':
            if start_time == end_time:
                leave_day = 1
            elif start_time > end_time:
                returnDict = {'code': 500, 'message': '创建失败！开始日期不能超过结束日期！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                leave_day = demo(start_time, end_time)
        else:
            leave_day = 173

        if not end_time:
            end_time = "待定"

        if request.user.company.id == 25 and people_type == '3':
            group_grade = 'F3'
        elif request.user.company.id == 25 and people_type != '3':
            group_grade = 'F1'
        else:
            if (company.is_functional is True) and (request.user.group.id == 6) and (people_type != '3'):
                group_grade = 'F1'
            elif request.user.group.id == 3:
                group_grade = 'C'
            elif request.user.group.id == 4:
                group_grade = 'D'
            elif request.user.group.id == 5:
                group_grade = 'E'
            elif request.user.group.id == 1:
                group_grade = 'A'
            elif request.user.group.id == 2:
                group_grade = 'B'
            elif request.user.group.id == 7:
                group_grade = 'C'
            elif (company.is_functional is False) and (request.user.group.id in [6, 7]) and (people_type != '3'):
                group_grade = 'F2'
            else:
                group_grade = 'F3'

        if id:
            obj = LeaveRequest.objects.get(id=id)
            obj.apply_user = apply_user
            obj.job_num = job_num
            obj.leave_type = leave_type
            obj.reason = reason
            obj.company = company
            obj.fj_number = fj_number
            obj.start_time = start_time
            obj.end_time = end_time
            obj.days = leave_day
            obj.group_grade = group_grade
            obj.people_type = people_type
            obj.save()
        else:
            obj = LeaveRequest.objects.create(apply_user=apply_user, job_num=job_num, leave_type=leave_type, reason=reason, start_time=start_time, company=company,
                                              fj_number=fj_number, end_time=end_time, days=leave_day, group_grade=group_grade, people_type=people_type)

        rsk_com = Company.objects.get(id=16)
        rsk_director = rsk_com.head_people      # 人事科负责人

        hlb_com = Company.objects.get(id=15)
        hlb_director = hlb_com.head_people      # 护理部负责人

        ywk_com = Company.objects.get(id=13)
        ywk_director = ywk_com.head_people      # 医务科负责人

        if group_grade == 'F3':
            ks_director = company.head_nurse_id if company.head_nurse_id else company.head_people         # 科室负责人
        else:
            ks_director = company.head_people         # 科室负责人

        fg_leaders = company.leaders_id         # 分管领导

        if leave_type == "d":
            if leave_day > 7:
                obj.delete()
                returnData = {'code': 400, 'message': '事假大于7天无法申请OA流程！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            flag = True
            if ks_director != apply_user:
                LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=ks_director, parent_id=obj)
                obj.state = "one"
                obj.save()
                flag = False
                obj.current_audit_users.add(ks_director)

            flag1, flag2 = True, True
            if leave_day > 1:
                print("=================================group_grade：", group_grade, leave_day)
                if group_grade in ['D', 'F2']:
                    two_setp = ywk_director
                elif group_grade in ['E', 'F3']:
                    two_setp = hlb_director
                else:
                    two_setp = ""

                if two_setp:
                    LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_setp, parent_id=obj)
                    if flag:
                        obj.state = "two"
                        obj.save()
                        flag1 = False
                        obj.current_audit_users.add(two_setp)

                if leave_day > 3:
                    LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=fg_leaders, parent_id=obj)
                    if flag and flag1:
                        obj.state = "three"
                        obj.save()
                        flag2 = False
                        obj.current_audit_users.add(fg_leaders)

            if request.user.group.id in [3, 4, 7] and not LeaveRequestAuditRecord.objects.filter(node='three', state='unaudit', parent_id=obj).count():
                LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=fg_leaders, parent_id=obj)
                if flag and flag1:
                    obj.state = "three"
                    obj.save()
                    flag2 = False
                    obj.current_audit_users.add(fg_leaders)

            LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=rsk_director, parent_id=obj)
            if flag and flag1 and flag2:
                obj.state = "four"
                obj.save()
                obj.current_audit_users.add(rsk_director)

        elif leave_type in ["e", "f", "g", "i", "j"]:
            alla_day, surplus = 0, 10
            if leave_type == 'j':
                DayObj = apply_user.leaverequesttypedays_set.filter(leave_type='j', years=time.strftime("%Y", time.localtime()))
                RequestedDay = int(DayObj.first().days) if DayObj else 0
                alla_day = RequestedDay + leave_day
                surplus = 10 - RequestedDay
            if leave_type in ["e", "f", "g"] and leave_day > 30:
                obj.delete()
                returnData = {'code': 400, 'message': '大于30天无法申请OA流程！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            if leave_type == "i" and leave_day > 42:
                obj.delete()
                returnData = {'code': 400, 'message': '大于42天无法申请OA流程！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            if (leave_type == "j" and leave_day > 10) or (leave_type == "j" and alla_day > 10):
                obj.delete()
                returnData = {'code': 400, 'message': f'剩余可用请假天数不足！剩余{surplus}天！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            flag = True
            if ks_director != apply_user:
                LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=ks_director, parent_id=obj)
                obj.state = "one"
                obj.save()
                flag = False
                obj.current_audit_users.add(ks_director)

            flag1, flag2 = True, True
            if leave_day > 3:
                if group_grade in ['D', 'F2']:
                    two_setp = ywk_director
                elif group_grade in ['E', 'F3']:
                    two_setp = hlb_director
                else:
                    two_setp = ""

                if two_setp:
                    LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_setp, parent_id=obj)
                    if flag:
                        obj.state = "two"
                        obj.save()
                        flag1 = False
                        obj.current_audit_users.add(two_setp)

                if leave_day > 7:
                    LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=fg_leaders, parent_id=obj)
                    if flag and flag1:
                        obj.state = "three"
                        obj.save()
                        flag2 = False
                        obj.current_audit_users.add(fg_leaders)

            LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=rsk_director, parent_id=obj)
            if flag and flag1 and flag2:
                obj.state = "four"
                obj.save()
                obj.current_audit_users.add(rsk_director)

        elif leave_type in ["a", "b", "c"]:
            alla_day, surplus = 0, 21
            if leave_type == 'a':
                DayObj = apply_user.leaverequesttypedays_set.filter(leave_type='a', years=time.strftime("%Y", time.localtime()))
                RequestedDay = int(DayObj.first().days) if DayObj else 0
                alla_day = RequestedDay + leave_day
                surplus = 21 - RequestedDay
            if (leave_type == 'a' and leave_day > 21) or (leave_type == 'a' and alla_day > 21):
                obj.delete()
                returnData = {'code': 400, 'message': f'年休假剩余天数不足！剩余{surplus}天！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            if leave_type in ["b", "c"] and leave_day > 3:
                obj.delete()
                returnData = {'code': 400, 'message': '请假天数不能超过3天！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            flag = True
            if ks_director != apply_user:
                LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=ks_director, parent_id=obj)
                obj.state = "one"
                obj.save()
                flag = False
                obj.current_audit_users.add(ks_director)

            flag1, flag2 = True, True

            if group_grade == 'D':
                two_setp = ywk_director
            elif group_grade == 'E':
                two_setp = hlb_director
            else:
                two_setp = ""

            if two_setp:
                LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_setp, parent_id=obj)
                if flag:
                    obj.state = "two"
                    obj.save()
                    flag1 = False
                    obj.current_audit_users.add(two_setp)
            if group_grade in ['C', 'D', 'E']:
                LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=fg_leaders, parent_id=obj)
                if flag and flag1:
                    obj.state = "three"
                    obj.save()
                    flag2 = False
                    obj.current_audit_users.add(fg_leaders)

            LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=rsk_director, parent_id=obj)
            if flag and flag1 and flag2:
                obj.state = "four"
                obj.save()
                obj.current_audit_users.add(rsk_director)

        else:
            if leave_day > 173:
                obj.delete()
                returnData = {'code': 400, 'message': '请假天数大于请假天数上线173天，请重新选择请假天数！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            flag = True
            if ks_director != apply_user:
                LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=ks_director, parent_id=obj)
                obj.state = "one"
                obj.save()
                flag = False
                obj.current_audit_users.add(ks_director)

            flag1, flag2 = True, True

            if group_grade in ['D', 'F2']:
                two_setp = ywk_director
            elif group_grade in ['E', 'F3']:
                two_setp = hlb_director
            else:
                two_setp = ""

            if two_setp:
                LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_setp, parent_id=obj)
                if flag:
                    obj.state = "two"
                    obj.save()
                    flag1 = False
                    obj.current_audit_users.add(two_setp)

            LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=fg_leaders, parent_id=obj)
            if flag and flag1:
                obj.state = "three"
                obj.save()
                flag2 = False
                obj.current_audit_users.add(fg_leaders)

            LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=rsk_director, parent_id=obj)
            if flag and flag1 and flag2:
                obj.state = "four"
                obj.save()
                obj.current_audit_users.add(rsk_director)
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "请假申请"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LeaveRequestApplyDraftView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        obj = LeaveRequest.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        leave_li = [
            {'value': 'a', 'leave': '年休假'},
            {'value': 'b', 'leave': '婚假'},
            {'value': 'c', 'leave': '丧假'},
            {'value': 'd', 'leave': '事假'},
            {'value': 'e', 'leave': '病假'},
            {'value': 'f', 'leave': '探亲假'},
            {'value': 'g', 'leave': '放射假'},
            {'value': 'h', 'leave': '产假'},
            {'value': 'i', 'leave': '计生假'},
            {'value': 'j', 'leave': '育儿假'},
        ]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, 'leave_li': leave_li}
        return render(request, 'finance/leave_request_apply_draft_view.html', context)

    def post(self, request):
        apply_user = request.user
        company = request.user.company
        job_num = request.user.job_number
        group_grade = request.user.group.level
        id = request.POST.get('id', None)
        leave_type = request.POST.get('leave_type', None)       # {'value': 'a', 'leave': '年休假'}
        reason = request.POST.get('reason', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        fj_number = request.POST.get('fj_number', None)
        leave_day = demo(start_time, end_time)
        people_type = request.POST.get('people_type', '')
        if id:
            obj = LeaveRequest.objects.get(id=id)
            obj.apply_user = apply_user
            obj.state = 'draft'
            obj.job_num = job_num
            obj.leave_type = leave_type
            obj.reason = reason
            obj.company = company
            obj.fj_number = fj_number
            obj.start_time = start_time
            obj.end_time = end_time
            obj.people_type = people_type
            obj.save()
        else:
            obj = LeaveRequest.objects.create(apply_user=apply_user, state='draft', job_num=job_num, leave_type=leave_type,
                                              reason=reason, start_time=start_time, company=company,
                                              fj_number=fj_number, end_time=end_time, people_type=people_type)

        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class LeaveRequestListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": 'finance_leaverequest'}
        return render(request, 'finance/leave_request_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办
        if tab == 'apply':
            objs = user.leaverequest_set.all().order_by('-create_time')
        elif tab == 'already':
            objs = user.leave_request_already_audit_users.all().order_by('-create_time')
        else:
            objs = user.leave_request_audit_users.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'leave_type': obj.get_leave_type(),
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='leave_request_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.state == 'draft' else (
                          f"<a href='leave_request_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                          if obj.state == 'stop' else f"<a href='leave_request_detail_view?id={obj.id}'>查看</a>"),
                      'state': obj.get_str_state()
                      }
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class LeaveRequestDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        id = request.GET.get("id", None)
        obj = LeaveRequest.objects.get(id=id)
        leave_li = [
            {'value': 'a', 'leave': '年休假'},
            {'value': 'b', 'leave': '婚假'},
            {'value': 'c', 'leave': '丧假'},
            {'value': 'd', 'leave': '事假'},
            {'value': 'e', 'leave': '病假'},
            {'value': 'f', 'leave': '探亲假'},
            {'value': 'g', 'leave': '放射假'},
            {'value': 'h', 'leave': '产假'},
        ]
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.leaverequestauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.leaverequestauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   "leave_type": obj.get_leave_type(),
                   'is_edit': 'true' if obj.state == 'eight' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'eight'] and request.user == obj.apply_user else 'false',
                   'user_obj': User.objects.filter(group_id=1),
                   "leave_li": leave_li, "flow_dict": flow_dict, "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/leave_request_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "请假申请")
        except:
            pass
        obj = LeaveRequest.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        leave_day = obj.days
        leave_type = obj.leave_type

        if obj.state == "one":
            audit_record = obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.leaverequestauditrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                elif obj.leaverequestauditrecord_set.filter(node='three', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "two":
            audit_record = obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "three":
            audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if leave_type in ["a", "j"]:
                    if request.user.leaverequesttypedays_set.filter(leave_type=leave_type, years=time.strftime("%Y", time.localtime())):
                        LeaveRequestTypeDays.objects.create(apply_user=request.user, leave_type=leave_type, days=leave_day, years=time.strftime("%Y", time.localtime()))
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "请假申请"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LeaveRequestRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = LeaveRequest.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.leaverequestauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LeaveRequestWriteView(View):
    def post(self, request):
        id = request.POST.get("id", None)
        xiugai = request.POST.get('xiugai', None)
        obj = LeaveRequest.objects.get(id=int(id))
        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        leave_type = request.POST.get('leave_type', None)
        reason = request.POST.get('reason', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)

        if start_time == end_time:
            leave_day = 1
        elif start_time > end_time:
            if leave_type != 'h':
                returnDict = {'code': 500, 'message': '创建失败！开始日期不能超过结束日期！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                leave_day = 173
        else:
            leave_day = demo(start_time, end_time)

        if leave_type:
            obj.leave_type = leave_type
        if reason:
            obj.reason = reason
        if start_time:
            obj.start_time = start_time
        if end_time:
            obj.end_time = end_time
        if leave_day:
            obj.days = leave_day

        obj.save()
        if not xiugai:
            obj.current_audit_users.clear()

            if obj.group_grade == "C":
                obj.state = 'three'
                if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                    audit_record_obj = obj.leaverequestauditrecord_set.filter(node='three').first()
                    LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                    audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                    LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                audit_record_obj = obj.leaverequestauditrecord_set.filter(node='three').last()
                obj.current_audit_users.add(audit_record_obj.audit_people)

            elif obj.group_grade == "D" or obj.group_grade == "E":
                obj.state = 'two'
                if obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').count() == 0:
                    audit_record_obj = obj.leaverequestauditrecord_set.filter(node='two').first()
                    LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                    audit_record_obj = obj.leaverequestauditrecord_set.filter(node='three').first()
                    LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                    audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                    LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                audit_record_obj = obj.leaverequestauditrecord_set.filter(node='two').last()
                obj.current_audit_users.add(audit_record_obj.audit_people)

            elif obj.group_grade == "F1":
                obj.state = 'one'
                leave_days = get_total_days(leave_type)
                if (obj.leave_type in ['a', 'b', 'c']) or (obj.leave_type in ['e', 'f', 'g'] and obj.days <= 3 and leave_days <= 7) or (obj.leave_type == 'd' and obj.days <= 1):
                    if obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='one').first()
                        LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                        LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                elif (obj.leave_type in ['d', 'h'] and 2 <= obj.days <= 7) or (obj.leave_type in ['e', 'f', 'g'] and obj.days >= 4) or (obj.leave_type in ['e', 'f', 'g'] and leave_days > 7):
                    if obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='one').first()
                        LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='three').first()
                        LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                        LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                audit_record_obj = obj.leaverequestauditrecord_set.filter(node='one').last()
                obj.current_audit_users.add(audit_record_obj.audit_people)

            else:
                leave_days = get_total_days(leave_type)
                obj.state = 'one'
                if (obj.leave_type in ['a', 'b', 'c']) or (obj.leave_type in ['e', 'f', 'g'] and obj.days <= 3 and leave_days <= 7) or (obj.leave_type == 'd' and obj.days <= 1):
                    if obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='one').first()
                        LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                        LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                elif (obj.leave_type in ['d', 'h'] and 2 <= obj.days <= 7) or (obj.leave_type in ['e', 'f', 'g'] and obj.days >= 4) or (obj.leave_type in ['e', 'f', 'g'] and leave_days > 7):
                    if obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='one').first()
                        LeaveRequestAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='two').first()
                        LeaveRequestAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='three').first()
                        LeaveRequestAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

                    if obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                        audit_record_obj = obj.leaverequestauditrecord_set.filter(node='four').first()
                        LeaveRequestAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                audit_record_obj = obj.leaverequestauditrecord_set.filter(node='two').last()
                obj.current_audit_users.add(audit_record_obj.audit_people)
        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 议题列表
class GetIssList(View):
    def post(self, request):
        iss_type = request.POST.get("iss_type", None)
        iss_number = request.POST.get("iss_number", None)
        IssYesr = request.POST.get("IssYesr", None)

        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_val", '')  # 查询标题
        xzshangdict, data_list, LeftDict = {}, [], {}

        if iss_type == 'yb':
            result_node = 'yb_result'
        elif iss_type == 'db':
            result_node = 'db_result'
        else:
            result_node = 'xz_result'
        toupiao_obj = topic_meeting.objects.filter(topic_type=iss_type, meet_number=iss_number, topic_year=IssYesr)
        if toupiao_obj:
            objs = toupiao_obj
            for ttt in toupiao_obj:
                if ttt.state == 'voting':
                    VotingResults = '投票中'
                elif ttt.state == 'adopt':
                    VotingResults = '通过'
                elif ttt.state in ['suspension', 'nopass']:
                    VotingResults = '暂缓'
                elif ttt.state == 'notstart':
                    VotingResults = '未开始'
                else:
                    VotingResults = '结束'
                data_list.append(
                    {'id': ttt.topic.id, 'title': ttt.topic.topics_name, 'IssueNumber': ttt.topic.number,
                     'department': ttt.topic.employee.company.name, 'is_yb': 1 if ttt.topic.is_yb else 0,
                     'relust': 1 if ttt.topic.topicsauditrecord_set.filter(node=result_node) else 0,
                     'is_audit': ttt.topic.is_audit,
                     'submitter': ttt.topic.employee.real_name,
                     'VotingResults': VotingResults,
                     'vote_id': ttt.id,
                     'SubmissionTime': ttt.topic.topicsauditrecord_set.filter(node__in=['YB/DB', 'YZ/SJ', 'sj']).order_by('update_time').last().update_time
                     })
        else:
            objs = Topics.objects.filter(Q(topics_name__contains=search_data) | Q(number__contains=search_data) | Q(employee__company__name__contains=search_data), type=iss_type, meetings_num=iss_number, iss_year=IssYesr)

            for obj in objs:
                TopMeetObj = obj.topic_meeting_set.all().first()
                if TopMeetObj:
                    if TopMeetObj.state == 'voting':
                        VotingResults = '投票中'
                    elif TopMeetObj.state == 'adopt':
                        VotingResults = '通过'
                    elif TopMeetObj.state == 'suspension':
                        VotingResults = '暂缓'
                    elif TopMeetObj.state == 'notstart':
                        VotingResults = '未开始'
                    else:
                        VotingResults = '结束'
                else:
                    VotingResults = '结束'

                data_list.append(
                    {'id': obj.id, 'title': obj.topics_name, 'IssueNumber': obj.number,
                     'department': obj.employee.company.name, 'is_yb': 1 if obj.is_yb else 0,
                     'relust': 1 if obj.topicsauditrecord_set.filter(node=result_node) else 0,
                     'is_audit': obj.is_audit,
                     'submitter': obj.employee.real_name,
                     'VotingResults': VotingResults,
                     'vote_id': obj.topic_meeting_set.all().first().id if obj.topic_meeting_set.all().first() else "",
                     'SubmissionTime': obj.topicsauditrecord_set.filter(node__in=['YB/DB', 'YZ/SJ', 'sj']).order_by('update_time').last().update_time
                     })

            data_list.sort(key=itemgetter('SubmissionTime'), reverse=False)

            for ij in data_list:
                if ij["department"] in xzshangdict:
                    xzshangdict[ij["department"]].append(ij)
                else:
                    xzshangdict[ij["department"]] = [ij]
            data_list = []
            for key, val in xzshangdict.items():
                for jjj in val:
                    data_list.append(jjj)

        DataList = []
        for ii in data_list:
            ii['SubmissionTime'] = str(ii['SubmissionTime']).split(".")[0][:-3]
            if ii["vote_id"]:
                vote_url = f'vote_detail.html?vote_id={ii["vote_id"]}&id={ii["id"]}'
            else:
                vote_url = "javascript:;"

            result_color = "red;" if ii["VotingResults"] == "暂缓" else "#727E8C;" if ii["VotingResults"] in ["notstart", "结束"] else "dodgerblue;"

            if iss_type == "yb":
                if not ii["is_audit"] and ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a style='color: #727E8C;' href='#'>完结</a>  | <a id='transfer_" + str(ii["id"]) + "' style='color: #727E8C;' href='#'>转会</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                elif not ii["is_audit"] and not ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a style='color: #727E8C;' href='#'>完结</a>  | <a id='transfer_" + str(ii["id"]) + "' style='color: dodgerblue;' href='#'>转会</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                elif ii["is_audit"] and ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a id='" + str(ii["id"]) + "' style='color: dodgerblue;' href='#' onclick='online_tag1(" + str(ii["id"]) + ',"audit"' + ", \""+ii["title"].strip()+"\", \""+ii["IssueNumber"]+"\")'>完结</a>  | <a id='transfer_" + str(ii["id"]) + "' style='color: #727E8C;' href='#'>转会</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                else:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a id='" + str(ii["id"]) + "' style='color: dodgerblue;' href='#' onclick='online_tag1(" + str(ii["id"]) + ',"audit"' + ", \""+ii["title"].strip()+"\", \""+ii["IssueNumber"]+"\")'>完结</a> | <a id='transfer_" + str(ii["id"]) + "' style='color: dodgerblue;' href='#')'>转会</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
            else:
                if ii["relust"] and ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a style='color: #727E8C;' href='#'>完结</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                elif ii["relust"] and not ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a style='color: #727E8C;' href='#'>完结</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                elif not ii["relust"] and ii["is_yb"]:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a id='" + str(ii["id"]) + "' style='color: dodgerblue;' href='#' onclick='online_tag1(" + str(ii["id"]) + ',"audit"' + ", \""+ii["title"]+"\", \""+ii["IssueNumber"]+"\")'>完结</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
                else:
                    urls = "<a style='color: "+result_color+"' href='"+vote_url+"'>"+ii["VotingResults"]+"</a> | <a id='" + str(ii["id"]) + "' style='color: dodgerblue;' href='#' onclick='online_tag1(" + str(ii["id"]) + ',"audit"' + ", \""+ii["title"]+"\", \""+ii["IssueNumber"]+"\")'>完结</a> | <a href='SubjectDetailst.html?views=1&id=" + str(ii["id"]) + "' target='_blank'>查看</a> | <a href='"+vote_url+"'>投票详情</a>"
            ii["url"] = urls
            DataList.append(ii)

        returnDict = {'status': 'success', "totals": objs.count(), "data": DataList[(int(page) - 1) * int(page_size):int(page) * int(page_size)], "LeftDict": LeftDict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 未上会议题列表
class NotMeetList(View):
    def post(self, request):
        iss_type = request.POST.get("iss_type", None)
        iss_number = request.POST.get("iss_number", None)
        IssYesr = request.POST.get("IssYesr", None)

        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_val", '')  # 查询标题

        objs = Topics.objects.filter(Q(topics_name__contains=search_data) | Q(number__contains=search_data) | Q(employee__company__name__contains=search_data),
               type=iss_type, state='done', is_meeting='a', meetings_num='0')

        data_list = [
            {'id': obj.id, "title": obj.topics_name, "IssueNumber": obj.number, "department": obj.employee.company.name,
             'submitter': obj.employee.real_name, 'SubmissionTime': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'AuditTime': obj.topicsauditrecord_set.filter(node='YB/DB').last().update_time.strftime("%Y-%m-%d %H:%M"),
             'meeting_num': obj.meetings_num, 'is_yb': 1 if obj.is_yb else 0} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]

        data_list.sort(key=itemgetter('AuditTime'), reverse=False)
        xzweidict = {}
        for ij in data_list:
            if ij["dep"] in xzweidict:
                xzweidict[ij["dep"]].append(ij)
            else:
                xzweidict[ij["dep"]] = [ij]

        YbWeiList = []
        for j in xzweidict:
            for k in xzweidict[j]:
                tttt = str(k["spsj"]).split(".")[0][:-3]
                k["spsj"] = tttt
                YbWeiList.append(k)

        returnDict = {'status': 'success', "totals": objs.count(), "data": YbWeiList}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 议题备注
class IssueRemarks(View):
    def get(self, request):
        iss_id = request.GET.get("iss_id", None)
        if iss_id:
            iss_obj = Topics.objects.get(id=int(iss_id))
            iss_obj.state = "unmetting"
            iss_obj.save()
            returnDict = {'status': 'success', "code": 200, "msg": ""}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'status': 'success', "code": 400, "msg": "请选择议题！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        iss_id = request.POST.get("iss_id", None)
        shelve = request.POST.get("shelve", None)           # 是否搁置
        remarks = request.POST.get("remarks", None)         # 备注
        halfway = request.POST.get("halfway", None)
        RecordAndPush().OperationRecords(request, "议题管搁置")
        topic_obj = Topics.objects.get(id=int(iss_id))
        if not halfway:
            if str(shelve) == "1":
                topic_obj.state = "shelve"  # 更改议题状态
                topic_obj.save()
            TopicsAuditRecord.objects.create(topics_id=topic_obj, audit_people=request.user, audit_note=remarks, state='audit', node='marks')
        else:
            try:
                RecordObj = TopicsAuditRecord.objects.get(topics_id=topic_obj, audit_people=request.user, state='unaudit')
                RecordObj.state = "shelve"
                RecordObj.audit_note = remarks
                RecordObj.update_time = datetime.now()
                RecordObj.save()
                topic_obj.last_state = topic_obj.state
                topic_obj.state = "shelve"  # 更改议题状态
                topic_obj.save()
                returnDict = {'status': 'success', 'code': 200, 'msg': '搁置成功！'}
                print(returnDict)
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            except Exception as E:
                if topic_obj.employee == request.user:
                    returnDict = {'status': 'success', 'code': 400, 'msg': '申请人无法搁置流程，可终止流程！'}
                else:
                    returnDict = {'status': 'success', 'code': 400, 'msg': '流程已审核，无法搁置！'}
                print(returnDict)
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', 'code': 200, 'msg': '添加备注成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 搁置议题列表
class Issue_Shelved(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.department}
        return render(request, 'personal_center/Issue_Shelved.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        iss_type = request.POST.get("iss_type", None)
        search_data = request.POST.get("search_data", "")  # 查询标题

        objs = Topics.objects.filter(Q(topics_name__contains=search_data) | Q(number__contains=search_data) | Q(employee__company__name__contains=search_data) | Q(employee__real_name__contains=search_data),
                                     state='shelve', type=iss_type)
        data_list = [{'id': obj.id, "title": obj.topics_name, "IssueNumber": obj.number, "department": obj.employee.company.name,
             'submitter': obj.employee.real_name, 'SubmissionTime': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'AuditTime': obj.topicsauditrecord_set.filter(node='YB/DB').last().update_time.strftime("%Y-%m-%d %H:%M"),
             'Reporter': obj.topicsauditrecord_set.filter(node='B').last().audit_people.real_name} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 来文备注
class comments(View):
    def post(self, request):
        received_id = request.POST.get("received_id", None)
        remarks = request.POST.get("remarks", None)
        document_obj = OfficialDocuments.objects.get(id=int(received_id))
        OfficialDocumentsAuditRecord.objects.create(official_documents_id=document_obj, state='audit', audit_people=request.user, audit_note=remarks, node="remarks")
        returnDict = {'status': 'success', 'code': 200, "message": ""}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 自定义申请列表
class CustomList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        flow_id = request.GET.get("id", '')
        print("=============flow_id: ", flow_id)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.department, "flow_id": flow_id}
        return render(request, 'personal_center/CustomList.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        custom_id = request.POST.get("id", None)
        cus_obj = CustomerForm.objects.get(id=int(custom_id))

        objs = cus_obj.lowcodebill_set.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id, "types": cus_obj.name, "apply_time": obj.create_time.strftime("%Y-%m-%d %H:%M"), 'apply': obj.apply_user.real_name, 'company': obj.apply_user.company.name,
                      'node': obj.get_state_str(), "current_audit_users": ' ,'.join([i.real_name for i in obj.current_audit_users.all()])
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 抄送流程
class CopyProcess(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.department}
        return render(request, 'personal_center/CopyProcess.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        change_tag = request.POST.get("change_tag", '0')
        Make_obj = MakeCopy.objects.filter(look_over=change_tag, recipient=request.user).order_by("-create_time")
        looked_list, look_list = [], []
        for obj in Make_obj[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if obj.type == 'a':
                try:
                    SealObj = SealApply.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "用印申请", "apply": SealObj.apply_user.real_name, "company": SealObj.apply_user.company.name, "Subject": SealObj.matter_type_text,
                                      "apply_time": SealObj.create_time.strftime("%Y-%m-%d %H:%M"), "url": f"/personal-center/seal_apply_detail_view?id={SealObj.id}"}
                except:
                    continue
            elif obj.type == 'c':
                try:
                    QuickObj = QuickAuthorization.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "快捷用印授权", "apply": QuickObj.apply_user.real_name,
                                      "company": QuickObj.apply_user.company.name, "Subject": json.loads(QuickObj.reason)[0]["neirong"],
                                      "apply_time": QuickObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/finance/QuickAuthorizationDetail.html?id={QuickObj.id}"}
                except:
                    continue
            elif obj.type == 'd':
                try:
                    PurchasingObj = PurchasingRequisition.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "服务申请", "apply": PurchasingObj.apply_user.real_name,
                                      "company": PurchasingObj.company.name, "Subject": PurchasingObj.ApplicationReason,
                                      "apply_time": PurchasingObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/logistics/ServiceProcurementDetail.html?id={PurchasingObj.id}"}
                except:
                    continue
            elif obj.type == 'e':
                try:
                    GoodsObj = GoodsProcure.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "货物采购", "apply": GoodsObj.apply_user.real_name,
                                      "company": GoodsObj.company.name, "Subject": GoodsObj.PurchaseReason,
                                      "apply_time": GoodsObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/logistics/GoodsProcureDetail.html?id={GoodsObj.id}"}
                except:
                    continue
            elif obj.type == 'f':
                try:
                    BusinessObj = BusinessContract.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "经济合同会签", "apply": BusinessObj.apply_user.real_name,
                                    "company": BusinessObj.company.name, "Subject": BusinessObj.contract_name,
                                    "apply_time": BusinessObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                    "url": f"/finance/business_contract_detail_view?id={BusinessObj.id}"}
                except:
                    continue
            elif obj.type == 'g':
                try:
                    MaintenanceObj = MaintenanceRenovation.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "维修改造", "apply": MaintenanceObj.apply_user.real_name,
                                      "company": MaintenanceObj.company.name, "Subject": MaintenanceObj.EntryName,
                                      "apply_time": MaintenanceObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/logistics/MaintenanceRenovationDetail.html?id={MaintenanceObj.id}"}
                except:
                    continue
            elif obj.type == 'h':
                try:
                    ComputerObj = ComputerDevice.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "计算机及相关设备购置", "apply": ComputerObj.apply_user.real_name,
                                      "company": ComputerObj.company.name, "Subject": ComputerObj.ApplicationReason,
                                      "apply_time": ComputerObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/logistics/ComputerDeviceDetail.html?id={ComputerObj.id}"}
                except:
                    continue
            elif obj.type == 'i':
                try:
                    ObjectObj = ObjectAudit.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "项目审计送审申请", "apply": ObjectObj.apply_user.real_name,
                                      "company": ObjectObj.company.name, "Subject": ObjectObj.work_name,
                                      "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/finance/object_audit_detail_view?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'j':
                try:
                    ObjectObj = BiddingProcurementProject.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "招标采购项目", "apply": ObjectObj.apply_user.real_name,
                                      "company": ObjectObj.company.name, "Subject": ObjectObj.ApplicationReason,
                                      "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                      "url": f"/logistics/BiddingProcurementProjectDetail.html?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'l':
                try:
                    ObjectObj = Topics.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "院办议题转党办", "apply": ObjectObj.employee.real_name,
                                "company": ObjectObj.employee.company.name, "Subject": ObjectObj.topics_name,
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/personal-center/SubjectDetailst.html?views=1&id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'm':
                try:
                    ObjectObj = TravelApply.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "差旅申请", "apply": ObjectObj.apply_user.real_name,
                                "company": ObjectObj.company.name, "Subject": ObjectObj.subject,
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/finance/travel_apply_detail_view?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'n':
                try:
                    ObjectObj = OutgoingCadresData.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "中层干部外出", "apply": ObjectObj.apply_user.real_name,
                                "company": ObjectObj.company.name, "Subject": ObjectObj.title,
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/finance/middle_level_detail.html?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'o':
                try:
                    ObjectObj = ConfidentialDataExport.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "敏感数据外导", "apply": ObjectObj.apply_user.real_name,
                                "company": ObjectObj.company.name, "Subject": ObjectObj.application_reason,
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/finance/data_export_detail.html?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'p':
                try:
                    ObjectObj = ContractApproval.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "经济合同会签流程", "apply": ObjectObj.apply_user.real_name,
                                "company": ObjectObj.apply_user.company.name, "Subject": ObjectObj.title,
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/finance/ContractDetail.html?id={ObjectObj.id}"}
                except:
                    continue
            elif obj.type == 'q':
                try:
                    ObjectObj = SupportSubsidies.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "体检科支援加班补助", "apply": ObjectObj.apply_user.real_name,
                                "company": ObjectObj.apply_user.company.name, "Subject": '体检科支援加班补助',
                                "apply_time": ObjectObj.create_time.strftime("%Y-%m-%d %H:%M"),
                                "url": f"/payment-management/OvertimeAllowanceDetail.html?id={ObjectObj.id}"}
                except:
                    continue
            else:
                try:
                    ConObj = ConferenceMemo.objects.get(id=int(obj.process_id))
                    one_dict = {"id": obj.id, "types": "行政公文", "apply": ConObj.apply_user.real_name, "company": ConObj.apply_user.company.name, "Subject": ConObj.conference_memo_text,
                                      "apply_time": ConObj.create_time.strftime("%Y-%m-%d %H:%M"), "url": f"/personal-center/document_detail.html?id={ConObj.id}"}
                except:
                    continue
            if obj.look_over == "1":
                one_dict['look_state'] = "已查看"
                look_list.append(one_dict)
            else:
                one_dict['look_state'] = "未查看"
                look_list.append(one_dict)

        returnDict = {'status': 'success', "totals": Make_obj.count(), "data": look_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class modify_state(View):
    def post(self, request):
        modify_id = request.POST.get("id", '')
        obj = MakeCopy.objects.get(id=int(modify_id))
        obj.look_over = "1"
        obj.update_time = datetime.now()
        obj.save()
        if obj.type == 'a':
            url = f"/personal-center/seal_apply_detail_view?id={obj.process_id}"
        elif obj.type == 'c':
            url = f"/finance/QuickAuthorizationDetail.html?id={obj.process_id}"
        elif obj.type == 'd':
            url = f"/logistics/ServiceProcurementDetail.html?id={obj.process_id}"
        elif obj.type == 'e':
            url = f"/logistics/GoodsProcureDetail.html?id={obj.process_id}"
        elif obj.type == 'f':
            url = f"/finance/business_contract_detail_view?id={obj.process_id}"
        elif obj.type == 'g':
            url = f"/logistics/MaintenanceRenovationDetail.html?id={obj.process_id}"
        elif obj.type == 'h':
            url = f"/logistics/ComputerDeviceDetail.html?id={obj.process_id}"
        elif obj.type == 'i':
            url = f"/finance/object_audit_detail_view?id={obj.process_id}"
        elif obj.type == 'j':
            url = f"/logistics/BiddingProcurementProjectDetail.html?id={obj.process_id}"
        elif obj.type == 'l':
            url = f"/personal-center/SubjectDetailst.html?views=1&id={obj.process_id}"
        elif obj.type == 'm':
            url = f"/finance/travel_apply_detail_view?id={obj.process_id}"
        elif obj.type == 'n':
            url = f"/finance/middle_level_detail.html?id={obj.process_id}"
        elif obj.type == 'o':
            url = f"/finance/data_export_detail.html?id={obj.process_id}"
        elif obj.type == 'p':
            url = f"/finance/ContractDetail.html?id={obj.process_id}"
        elif obj.type == 'q':
            url = f"/payment-management/OvertimeAllowanceDetail.html?id={obj.process_id}"
        else:
            url = f"/personal-center/document_detail.html?id={obj.process_id}"
        returnDict = {'status': 'success', "url": url, "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 自定义流程申请
class CustomProcessIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        flow_id = request.GET.get("flow_id", '')
        obj = CustomerForm.objects.get(id=int(flow_id))
        record_list = deal_templates_html(obj.business_html)
        company_list = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        context = {'data': {'business_html': urllib.parse.unquote(base64.b64decode(obj.business_html).decode()), 'process_html': obj.process_html, "name": obj.name, "record_list": record_list, "id": obj.id},
                   'realname': request.user.real_name,
                   'position': request.user.post, 'flow_id': flow_id,
                   'department': request.user.company.name,
                   'uuid': uuid.uuid1(), 'company_list': company_list}
        return render(request, 'personal_center/CustomProcessIndex.html', context)

class CustomProcessDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id')
        obj = LowCodeBill.objects.get(id=int(id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number, file_type="0")]

        audit_dic, flow_dict = {}, []
        for audit_obj in obj.lowcodebillauditrecord_set.all().order_by('seq'):
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.node,
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.lowcodebillauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict.append({'apply': apply, 'apply_people': ','.join(list(set(apply_people))), "node": audit_obj.node, 'sear': len([i for i in flow_dict]) + 1})
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.node,
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        record_list = deal_templates_html(obj.customer_form.business_html)
        context = {
            'data': {'business_html': urllib.parse.unquote(base64.b64decode(obj.data_html).decode()), 'cus_id': obj.customer_form.id,
                     "name": obj.customer_form.name, "data_html": obj.data_html, "audit_list": audit_dic, "file_list": file_list,
                     "is_audit": 'true' if request.user in obj.current_audit_users.all() and obj.state == 'one' else 'false',
                     "record_list": record_list, "id": obj.id, "uuid": obj.fj_number},
            'realname': request.user.real_name,
            'position': request.user.post,
            "is_edit": 'true' if (request.user in obj.current_audit_users.all() and obj.state == 'four') else 'false',
            'department': request.user.department, 'obj': obj, 'flow_dict': flow_dict,
            'file_path': file_list[0]['file_path'] if file_list else '', 'check_val': obj.check_val if obj.check_val else []
        }
        return render(request, 'personal_center/CustomProcessDetail.html', context)


class ExternalCorrespondenceList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        # 换成上级来文的列表
        return render(request, "personal_center/ExternalCorrespondenceList.html",
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", "")  # 查询标题
        objs = Correspondence.objects.filter(Q(title__contains=search_data) |
                                                  Q(recive_number__contains=search_data) |
                                                  Q(send_company__contains=search_data), apply_user=user).order_by('-create_time')

        review_list, distributed, return_list, circulation, end_list, cancel_list, stop_list, recall_list = [], [], [], [], [], [], [], []
        for obj in objs:
            one_dict = {'id': obj.id, 'title': obj.title, 'send_company': obj.send_company,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.get_state_str(), 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'send_number': obj.send_number, 'recive_number': obj.recive_number, 'state_display': obj.get_state_str(),
             "url": f"<a href='ExternalCorrespondenceDetail.html?id={obj.id}'>查看</a> | <a href='javascript:;' id='{obj.id}' onclick='model_inlone(this.id)'>备注</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.type == 'stop' else f"<a href='ExternalCorrespondenceDetail.html?id={obj.id}'>查看</a> | <a href='javascript:;' id='{obj.id}' onclick='model_inlone(this.id)'>备注</a>"}
            if obj.type == "seven":
                distributed.append(one_dict)
            elif obj.type == "six":
                return_list.append(one_dict)
            elif obj.type == "five":
                end_list.append(one_dict)
            elif obj.type == "four":
                circulation.append(one_dict)
            elif obj.type == "cancel":
                cancel_list.append(one_dict)
            elif obj.type == "stop":
                stop_list.append(one_dict)
            elif obj.type == "recall":
                recall_list.append(one_dict)
            else:
                review_list.append(one_dict)
        data_list = review_list + return_list + distributed + stop_list + recall_list + cancel_list + circulation + end_list
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ExternalCorrespondenceIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        today_data = time.strftime("%Y-%m-%d", time.localtime())
        today = datetime.now().date()
        lw_count = '函' + today_data + "-" + str(Correspondence.objects.filter(~Q(state='recall'), create_time__gt=today).count() + 1)
        charge_flag = True if request.user == Company.objects.get(id=80).head_people else False
        leaders_obj = User.objects.filter(group_id__in=[1, 2])
        return render(request, "personal_center/ExternalCorrespondenceIndex.html", {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid1(),
                                                                                    "lw_count": lw_count, "charge_flag": charge_flag, "leaders_obj": leaders_obj})

    def post(self, request):
        send_number = request.POST.get('send_number', None)
        recive_number = request.POST.get('recive_number', None)
        send_company = request.POST.get('send_company', None)
        recive_time = request.POST.get('recive_time', None)
        title = request.POST.get('title', None)
        content = request.POST.get('content', None)
        annotated_text = request.POST.get('annotated_text', '')
        time_limit = request.POST.get('time_limit', '')
        uuid = request.POST.get('uuid', '')
        rake_up = request.POST.get("rake_up", None)
        beizhu = request.POST.get("beizhu", None)
        leaders_people = request.POST.get("leaders_people", None)
        charge_flag = request.POST.get("charge_flag", None)

        today_data = time.strftime("%Y-%m-%d", time.localtime())
        today = datetime.now().date()
        lw_count = today_data + "-" + str(Correspondence.objects.filter(~Q(state='recall'), create_time__gt=today).count() + 1)

        recive_time = datetime.now().strptime(recive_time, '%Y-%m-%d %H:%M:%S')
        if rake_up:
            official_documents_obj = Correspondence.objects.get(uuid=uuid)
            official_documents_obj.current_audit_users.clear()
            official_documents_obj.correspondencerecord_set.filter(state='unaudit').delete()
            official_documents_obj.recive_time = recive_time
            official_documents_obj.send_company = send_company
            official_documents_obj.title = title
            official_documents_obj.content = content
            official_documents_obj.annotated_text = annotated_text
            official_documents_obj.time_limit = time_limit
            official_documents_obj.remarks = beizhu
            official_documents_obj.type = 'a'
            official_documents_obj.state = 'a'
            official_documents_obj.save()

        else:
            official_documents_obj = Correspondence.objects.create(apply_user=request.user, send_number=send_number,
                                                                      recive_number=lw_count,
                                                                      send_company=send_company,
                                                                      recive_time=recive_time,
                                                                      title=title,
                                                                      content=content, annotated_text=annotated_text,
                                                                      time_limit=time_limit, uuid=uuid, remarks=beizhu)

        if charge_flag == "True" or request.user == Company.objects.get(id=80).head_people:
            official_documents_obj.leaders = User.objects.get(id=leaders_people)
            official_documents_obj.state = "two"
            official_documents_obj.current_audit_users.add(User.objects.get(id=leaders_people))
            CorrespondenceRecord.objects.create(official_documents_id=official_documents_obj, state="unaudit", audit_people=User.objects.get(id=leaders_people), node="two")
            openid = User.objects.get(id=leaders_people).openid
        else:
            official_documents_obj.state = "one"
            official_documents_obj.current_audit_users.add(Company.objects.get(id=80).head_people)
            CorrespondenceRecord.objects.create(official_documents_id=official_documents_obj, state="unaudit", audit_people=Company.objects.get(id=80).head_people, node="one")
            openid = Company.objects.get(id=80).head_people.openid

        topic_type = "外部来函"
        applicant = official_documents_obj.apply_user.real_name
        ApplicationTime = official_documents_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = official_documents_obj.title[:15] + "……" if len(official_documents_obj.title) > 15 else official_documents_obj.title
        try:
            RecordAndPush().MessagePush(openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        except:
            pass
        official_documents_obj.save()
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

def unagree_official(obj, audit_record_obj, audit_note, request):
    """外部来函退回调用函数"""
    obj.current_audit_users.clear()
    obj.current_audit_users.add(obj.apply_user)
    obj.type = 'six'
    obj.save()
    audit_record_obj.update_time = datetime.now()
    audit_record_obj.state = 'draft'
    audit_record_obj.audit_note = audit_note
    audit_record_obj.save()

class ExternalCorrespondenceDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = Correspondence.objects.get(id=int(id))

        p_obj = obj.correspondencepeople_set.filter(audit_people=request.user, state='accept').first()
        if p_obj:
            p_obj.state = 'accepted'
            p_obj.update_time = datetime.now()
            p_obj.save()

        if int(id) <= 4:
            if obj.correspondencepeople_set.filter(state='accept').count() == 0 and obj.type == 'four':
                obj.type = 'five'
                obj.save()

            approve_flag = ""
            if request.user in obj.current_audit_users.all():
                approve_flag = True
            file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                          "file_path": atta_obj.pdf_path.replace("\\", '/'),
                          "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                          "file_size": atta_obj.file_size,
                          "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                          'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                          "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                          "topics_number": atta_obj.topics_number} for atta_obj in
                         Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="0")]

            file_list1 = [{"file_name": atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", '/')} for atta_obj in
                          Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="1")]

            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.correspondencerecord_set.filter(~Q(node='eight')):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                      'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            appave_count = obj.correspondencerecord_set.filter(~Q(node='eight')).values("audit_people").distinct().count()

            recive_people, no_recive, recive = [], [], []
            for record in obj.correspondencepeople_set.all():
                one_dict = {'user': record.audit_people.real_name, 'state': record.get_state_display(),
                              'signature_picture': '/media/' + str(record.audit_people.signature_picture) if (record.audit_people.signature_picture and record.state == 'accepted') else '',
                              'update_time': record.update_time.strftime("%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                recive_people.append(one_dict)
                if record.state == 'accept':
                    no_recive.append(one_dict)
                else:
                    recive.append(one_dict)

            staff_obj = Staffing.objects.filter(station="办公室")

            flag = 0
            if staff_obj:
                for tt in staff_obj:
                    personnel = tt.post_personnel.all()
                    for jj in personnel:
                        if jj == request.user:
                            flag = 1

            data_dic = {
                'id': obj.id, 'appave_count': appave_count, 'yes_count': len(recive), 'recive': recive,
                'node': obj.get_type_display(), 'no_count': len(no_recive), 'no_recive': no_recive,
                'type': obj.type, 'all_count': len(recive_people), 'recive_people': recive_people,
                'apply_user': obj.apply_user.real_name, 'department': obj.apply_user.department, 'send_number': obj.send_number,
                'recive_number': obj.recive_number, 'title': obj.title, "uuid": obj.uuid, 'send_company': obj.send_company, 'content': obj.content,
                'annotated_text': obj.annotated_text, 'time_limit': obj.time_limit, 'remarks': obj.remarks, 'file_list': file_list,
                'flag': flag, 'fenfa_flag': 'true' if obj.type == 'eight' and request.user == obj.apply_user else 'flase', 'file_list1': file_list1,
                'recive_time': obj.recive_time.strftime("%Y-%m-%d %H:%M"), 'revocation_flag' : 'true',  # 撤回标签，’true‘ 有该权限
                'file_path': Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else "",
                'is_stop': 'true' if obj.type in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight'] and request.user == obj.apply_user else 'false',
            }
            returnDict = {'realname': real_name, 'position': position, 'department': department, 'data_dic': data_dic, "audit_dic": audit_dic, "approve_flag": approve_flag}
            return render(request, "personal_center/ExternalCorrespondenceDetail.html", returnDict)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.correspondencerecord_set.filter(~Q(node='eight')):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.correspondencerecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.uuid)]

            ReceivingObj = obj.correspondencepeople_set.all()
            ReceivingList = []
            for receiving in ReceivingObj:
                ReceivingList.append({"receiving": receiving.audit_people.real_name, "time": receiving.update_time.strftime("%Y-%m-%d %H:%M"), "state": receiving.state,
                                      "signature_picture": '/media/' + str(receiving.audit_people.signature_picture) if receiving.audit_people.signature_picture else ''})

            withdrawal = "false"
            received_obj = obj.correspondencerecord_set.filter(audit_people=request.user, state="audit")
            if received_obj.count():
                if received_obj.last().node == "one" and obj.state == "two":
                    withdrawal = "true"
                elif received_obj.last().node == "two" and obj.state == "three":
                    withdrawal = "true"
                elif received_obj.last().node == "three" and (obj.state == "three" or obj.state == "four"):
                    withdrawal = "true"
                elif received_obj.last().node == "four" and obj.state == "five":
                    withdrawal = "true"
                else:
                    withdrawal = "false"

            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                       'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) else 'false',
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                       'uuid': obj.uuid, 'flow_dict': flow_dict, "ReceivingList": ReceivingList, "withdrawal": withdrawal,
                       "leader_obj": User.objects.filter(group_id__in=[1, 2]),
                       'file_path': Topicsattachments.objects.filter(
                           topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(
                           topics_number=obj.uuid) else ""
                       }
            return render(request, "personal_center/ExternalCorrespondenceDetailNew.html", context)

    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get("state", 'audit')                                            # draft 拒绝 audit 通过
        audit_note = request.POST.get('audit_note', '同意')
        fg_people = request.POST.get('fg_people', None)                                                          # 分管人员
        type = request.POST.get('type', None)                                                # a 留文归档 b 拟办意见 c 党办 d 院办
        obj = Correspondence.objects.get(id=int(id))

        topic_type = "外部来函"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        RecordAndPush().OperationRecords(request, topic_type)

        if not type and obj.type == 'a':
            returnDict = {'code': 500, 'message': '办公室主任审核需指定类型'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.audit_users_already.add(request.user)

        if type and obj.type == 'one':
            obj.current_audit_users.clear()
            audit_record_obj = obj.correspondencerecord_set.filter(node='one', state='unaudit').first()
            audit_record_obj.update_time = datetime.now()
            audit_record_obj.state = 'audit'
            audit_record_obj.audit_note = audit_note
            audit_record_obj.save()
            obj.state = type
            obj.correspondencerecord_set.filter(state='unaudit').delete()
            if type == 'a':
                obj.type = 'five'
                obj.save()
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'b':
                obj.type = 'three'
                obj.save()

                fg_people = re.findall('\((.*?)\)', fg_people)
                fg_people_objs = User.objects.filter(job_number__in=fg_people)

                for fg_people_obj in fg_people_objs:
                    CorrespondenceRecord.objects.create(official_documents_id=obj, audit_people=fg_people_obj, audit_note='', node='three')
                    obj.current_audit_users.add(fg_people_obj)
                    try:
                        RecordAndPush().MessagePush(fg_people_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'c':
                obj.type = 'two'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.add(Staffing.objects.get(station="书记").post_personnel.all().first())
                try:
                    RecordAndPush().MessagePush(Staffing.objects.get(station="书记").post_personnel.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                CorrespondenceRecord.objects.create(official_documents_id=obj, state='unaudit', node='two', audit_note='', audit_people=Staffing.objects.get(station="书记").post_personnel.all().first())
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'd':
                obj.type = 'two'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.add(Staffing.objects.get(station="院长").post_personnel.all().first())
                try:
                    RecordAndPush().MessagePush(Staffing.objects.get(station="院长").post_personnel.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                CorrespondenceRecord.objects.create(official_documents_id=obj, state='unaudit', node='two', audit_note='', audit_people=Staffing.objects.get(station="院长").post_personnel.all().first())

                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'e':
                obj.type = 'two'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                yz_obj = Staffing.objects.get(station="院长").post_personnel.all().first()
                sj_obj = Staffing.objects.get(station="书记").post_personnel.all().first()

                CorrespondenceRecord.objects.create(official_documents_id=obj, state='unaudit', node='two', audit_note='', audit_people=yz_obj)
                CorrespondenceRecord.objects.create(official_documents_id=obj, state='unaudit', node='two', audit_note='', audit_people=sj_obj)
                obj.current_audit_users.add(yz_obj)
                try:
                    RecordAndPush().MessagePush(yz_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                obj.current_audit_users.add(sj_obj)
                try:
                    RecordAndPush().MessagePush(sj_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'f':
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'g':
                items = []
                receive_people = re.findall('\((.*?)\)', fg_people)
                receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                mobile_list = []
                for receive_people_obj in receive_people_objs:
                    mobile_list.append(receive_people_obj.mobile)
                    off_obj = CorrespondencePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                    items.append(off_obj)
                obj.current_audit_users.clear()
                CorrespondencePeople.objects.bulk_create(items)
                if receive_people:
                    obj.type = 'four'
                else:
                    obj.type = 'five'
                obj.save()
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                returnDict = {'code': 500, 'message': '指定类型错误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'two':
            audit_record_list = obj.correspondencerecord_set.filter(node='two', state='unaudit')
            audit_record_obj = None
            for i in audit_record_list:
                if i.audit_people == request.user:
                    audit_record_obj = i
            if state == 'audit':
                if audit_record_list.count() == 1:
                    obj.current_audit_users.clear()
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.state = 'audit'
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.save()
                    CorrespondenceRecord.objects.create(official_documents_id=obj, audit_people=obj.apply_user, audit_note='', node='eight')
                    obj.current_audit_users.add(obj.apply_user)
                    obj.type = 'eight'
                    obj.save()
                    try:
                        RecordAndPush().MessagePush(obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    obj.current_audit_users.remove(request.user)
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.state = 'audit'
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.save()

                returnDict = {'code': 200, 'message': '操作成功'}

                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'three':
            audit_record_obj = obj.correspondencerecord_set.filter(node='three', audit_people=request.user, state='unaudit').first()
            if state == 'audit':
                audit_record_obj.update_time = datetime.now()
                audit_record_obj.state = 'audit'
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.remove(request.user)
                if obj.correspondencerecord_set.filter(state='unaudit', node='three'):
                    pass
                else:
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.type = 'seven'
                    obj.save()
                    try:
                        RecordAndPush().MessagePush(obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'eight':
            audit_record_obj = obj.correspondencerecord_set.filter(node='eight', state='unaudit').first()

            obj.current_audit_users.clear()
            audit_record_obj.update_time = datetime.now()
            audit_record_obj.state = 'audit'
            audit_record_obj.audit_note = audit_note
            audit_record_obj.save()
            fg_people = re.findall('\((.*?)\)', fg_people)
            fg_people_objs = User.objects.filter(job_number__in=fg_people)

            for fg_people_obj in fg_people_objs:
                CorrespondenceRecord.objects.create(official_documents_id=obj, audit_people=fg_people_obj, audit_note='', node='three')
                obj.current_audit_users.add(fg_people_obj)
                try:
                    RecordAndPush().MessagePush(fg_people_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
            obj.type = 'three'
            obj.save()
            returnDict = {'code': 200, 'message': '操作成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'seven':
            pass

        else:
            print("参数错误")
            returnDict = {'code': 500, 'message': '参数错误'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ExternalCorrespondenceFinish(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Correspondence.objects.get(id=int(id))
        # if obj.apply_user != request.user:
        #     returnData = {'code': 500, 'message': '终止失败！只有申请人才能终止流程'}
        #     return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        obj.correspondencerecord_set.filter(state='unaudit').delete()
        obj.type = 'five'
        obj.save()
        returnData = {'code': 200, 'message': '流程结束成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ExternalCorrespondenceReceive(View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        message = request.POST.get('message', None)
        obj = Correspondence.objects.get(id=int(id))
        items = []
        receive_people = re.findall('\((.*?)\)', receive_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
        mobile_list = []
        for receive_people_obj in receive_people_objs:
            mobile_list.append(receive_people_obj.mobile)
            off_obj = CorrespondencePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
            items.append(off_obj)
        obj.current_audit_users.clear()
        CorrespondencePeople.objects.bulk_create(items)
        if receive_people:
            obj.type = 'four'
        else:
            obj.type = 'five'
        obj.save()
        if str(message) == '1':
            message_str = f'外部来函：您有一份“{obj.recive_number}”“{obj.title}”的外部来函需要处理接收，请您在OA系统上查收。'
            send_mssage(mobile_list, message_str)
        returnDict = {'code': 200, 'message': '操作成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class LetterManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/LetterManagement.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'audit')  # audit 我的待办 already 我的已办
        if tab == 'audit':
            objs = user.correspondence_users.all().order_by('-create_time')
        else:
            objs = user.correspondence_already_audit_users.all().order_by('-create_time')
        data_list = [
            {'id': obj.id, 'title': obj.title, 'send_company': obj.send_company,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.type, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
             'send_number': obj.send_number, 'recive_number': obj.recive_number, 'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        print(data_list)
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class lncoming_letter_receipt(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/lncoming_letter_receipt.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'accept')  # accept 未接受 accepted 已接收
        if tab == 'accept':
            objs = user.correspondencepeople_set.filter(state='accept').order_by("-create_time")
        else:
            objs = user.correspondencepeople_set.filter(state='accepted').order_by("-create_time")
        record_list = [record.notice_id for record in objs]
        data_list = [
            {'id': obj.id, 'send_company': obj.send_company, 'send_number': obj.send_number,
             'recive_time': obj.recive_time.strftime("%Y-%m-%d"), 'title': obj.title,
             'state': obj.get_type_display(), 'recive_number': obj.recive_number,
             'user': obj.apply_user.real_name, 'department': obj.apply_user.company.name,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             } for obj in
            record_list[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": len(record_list), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class filing_incoming_letters_view(View):
    def get(self, request):
        user = request.user
        page = request.GET.get("page", 1)
        cuent_type = request.GET.get('cuent_type', '0')
        accept_objs = user.correspondencepeople_set.filter(state='accept').order_by("-create_time")
        accepted_objs = user.correspondencepeople_set.filter(state='accepted').order_by("-create_time")
        end_objs = Correspondence.objects.filter(type='five').order_by("-create_time")
        accept_objs = [record.notice_id for record in accept_objs]
        accept_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                        'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                        'state': record.get_type_display(), 'recive_number': record.recive_number,
                        'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                        'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                        } for record
                       in accept_objs[(int(page) - 1) * 20:int(page) * 20]]
        accepted_objs = [record.notice_id for record in accepted_objs]
        accepted_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                          'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                          'state': record.get_type_display(), 'recive_number': record.recive_number,
                          'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                          'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                          } for record
                         in accepted_objs[(int(page) - 1) * 20:int(page) * 20]]

        end_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                     'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                     'state': record.get_type_display(), 'recive_number': record.recive_number,
                     'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                     'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                     } for record
                    in end_objs[(int(page) - 1) * 20:int(page) * 20]]

        if cuent_type == '0':
            returnData = {'code': 200, 'message': '获取成功！', 'accept_list': accept_list, 'len_accept': len(accept_objs), 'accepted_list': accepted_list, 'len_accepted_list': len(accepted_objs), 'end_list': end_list, 'end_list_len': end_objs.count()}
        elif cuent_type == '1':
            returnData = {'code': 200, 'message': '获取成功！', 'accept_list': accept_list, 'len_accept': len(accept_objs)}
        elif cuent_type == '2':
            returnData = {'code': 200, 'message': '获取成功！', 'accepted_list': accepted_list, 'len_accepted_list': len(accepted_objs)}
        else:
            returnData = {'code': 200, 'message': '获取成功！', 'end_list': end_list, 'end_list_len': end_objs.count()}

        return HttpResponse(json.dumps(returnData), content_type="application/json")

class filing_incoming_letters(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/filing_incoming_letters.html", {'realname': real_name, 'position': position, 'department': department})

class OfficialDocumentSubmission(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        return render(request, "personal_center/OfficialDocumentSubmission.html", {'realname': real_name, 'position': position, 'department': department})

class end_flows(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        end_reason = request.POST.get("end_reason", '')

        flow_obj = ConferenceMemo.objects.get(id=int(flow_id))
        flow_obj.conferencememoauditrecord_set.filter(state='unaudit').delete()
        flow_obj.current_audit_users.clear()
        flow_obj.state = "seven"
        flow_obj.save()

        ConferenceMemoAuditRecord.objects.create(conference_memo_id=flow_obj, audit_people=request.user, audit_note=end_reason, node='end', state="audit")
        returnDict = {'status': 'success', 'message': '操作成功！', 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class RestoringIssues(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", '')

        flow_obj = Topics.objects.get(id=int(flow_id))
        flow_obj.state = flow_obj.last_state
        flow_obj.last_state = ""
        flow_obj.save()
        try:
            RecordObj = TopicsAuditRecord.objects.filter(topics_id=flow_obj, audit_people=request.user, state='shelve').first()
            TopicsAuditRecord.objects.create(topics_id=flow_obj, audit_people=request.user, audit_note="", state='unaudit', node=RecordObj.node)
            returnDict = {'status': 'success', 'message': '操作成功！', 'code': 200}
        except Exception as E:
            returnDict = {'status': 'success', 'message': '还原失败！', 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UnderMaintenance(View):
    def get(self, request):
        return render(request, "personal_center/UnderMaintenance.html")

class ConfirmAttendance(View):
    def get(self, request):
        topic_type = request.GET.get("type", '')
        topic_year = request.GET.get("year", '')
        topic_num = request.GET.get("number", '')
        return render(request, "personal_center/ConfirmAttendance.html", {"topic_type": topic_type, "topic_year": topic_year, "topic_num": topic_num})